题目浅析

  • 想查看原题可以点击题目链接

  • 简单地说,就是给一个排序过的链表,现在要去除其中重复的元素结点。

思路分享

代码解答(强烈建议自行解答后再看)

  • 参考题解
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
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def deleteDuplicates(self, head: Optional[ListNode]) -> Optional[ListNode]:
if not head:
return head
cur = head
while cur.next:
if cur.val == cur.next.val:
cur.next = cur.next.next
else:
cur = cur.next
return head

if not head:
return head
last = head
cur = head.next
while cur:
if cur.val == last.val:
last.next = cur.next
else:
last = last.next
cur = cur.next
return head