将有序链表中重复出现的元素删除,每个元素出现一次。

题目

给定一个排序链表,删除所有重复的元素,使得每个元素只出现一次。

示例

示例 1:

输入: 1->1->2
输出: 1->2

示例 2:

输入: 1->1->2->3->3
输出: 1->2->3

题解

方法一

仅用一个指针

通过将结点的值与它之后的结点进行比较来确定它是否为重复结点。如果它是重复的,我们更改当前结点的 next 指针,以便它跳过下一个结点并直接指向下一个结点之后的结点。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def createLink_rearinsert(lista):
head = ListNode(-1)
rear = head
for i in lista:
new_node=ListNode(i)
rear.next=new_node
rear=new_node
return head.next
class Solution(object):
def deleteDuplicates(self, head):
if not (head and head.next):
return head
current=head
while current!=None and current.next!=None:
if current.next.val==current.val:
current.next=current.next.next
else:
current=current.next
return head

if __name__=="__main__":
a=[1,1,1,2,4,4]
new_a=createLink_rearinsert(a)
a1 = Solution()
p=a1.deleteDuplicates(new_a)
list1=[]
while(p!=None):
list1.append(p.val)
#print(p.val)
p=p.next
print(list1)
[1, 2, 4]

方法二

使用了两个指针

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def createLink_rearinsert(lista):
head = ListNode(-1)
rear = head
for i in lista:
new_node=ListNode(i)
rear.next=new_node
rear=new_node
return head.next
class Solution(object):
def deleteDuplicates(self, head):
if not (head and head.next):
return head
a = head
b = head.next
while b:
if a.val!=b.val:
a=b
b=b.next
else:
while b and a.val==b.val:
b = b.next

a.next = b
a=b
b = b.next if b else None
return head

if __name__=="__main__":
a=[1,1,1,2,4,4]
new_a=createLink_rearinsert(a)
a1 = Solution()
p=a1.deleteDuplicates(new_a)
list1=[]
while(p!=None):
list1.append(p.val)
#print(p.val)
p=p.next
print(list1)
[1, 2, 4]