Leetcode 82

Question

Solution

首先创建两个指针:pre, cur。pre指向空,cur指向head。如果出现多个相同元素,cur向后移动直到指向新的元素,pre.next指向cur。如果元素不重叠,pre移到cur的位置,cur向后移动一位。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None

class Solution:
def deleteDuplicates(self, head: ListNode) -> ListNode:
ans = pre = ListNode(0)
ans.next = head
cur = head
while cur:
if cur.next and cur.val == cur.next.val:
temp = cur.val
while cur and cur.val == temp:
cur = cur.next
pre.next = cur
else:
pre = cur
cur = cur.next
return ans.next