给定一个排序链表,删除所有重复的元素,使得每个元素只出现一次。
示例 1:
输入: 1->1->2
输出: 1->2
示例 2:
输入: 1->1->2->3->3
输出: 1->2->3
根据题目描述可知,最后的链表中每个元素只出现一次,那么在遍历链表时就要看后面的元素是否和当前指针所指元素相同
-
如果不同,则继续往后,更新
cur = cur.next
-
如果相同,则执行
cur.next = cur.next.next
,删除重复的元素,继续判断
AC code
class Solution:
def deleteDuplicates(self, head: ListNode) -> ListNode:
if head == None: return None
cur = head
while cur and cur.next:
if cur.next.val == cur.val:
cur.next = cur.next.next
else:
cur = cur.next
return head