跳到主要内容

Remove Duplicates from Sorted List

描述

Given a sorted linked list, delete all duplicates such that each element appear only once.

For example,

Given 1->1->2, return 1->2.

Given 1->1->2->3->3, return 1->2->3.

分析

代码

# Remove Duplicates from Sorted List
# 时间复杂度O(n),空间复杂度O(1)
class Solution:
def deleteDuplicates(self, head):
p = head
while p and p.next:
if p.next.val == p.val:
tmp = p.next
p.next = p.next.next
del tmp
else:
p = p.next
return head

相关题目