给定一个排序链表,删除所有重复的元素,使得每个元素只出现一次。
示例 1:
输入: 1->1->2
输出: 1->2
示例 2:
输入: 1->1->2->3->3
输出: 1->2->3
1.递归版:
class Solution(object):
def deleteDuplicates(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if not head or not head.next:return head
head.next = self.deleteDuplicates(head.next)
return head.next if head.val == head.next.val else head
2.1循环版:
class Solution(object):
def deleteDuplicates(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if not head:return
pre,cur = head,head.next
while cur:
if pre.val == cur.val:
cur = cur.next
pre.next = cur
else:
cur = cur.next
pre = pre.next
return head
2.2优化下代码:
class Solution(object):
def deleteDuplicates(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if not head:return
cur = head
while cur.next:
if cur.next.val == cur.val:
cur.next = cur.next.next
else:
cur = cur.next
return head
3.使用虚拟头结点版:
class Solution(object):
def deleteDuplicates(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
dummyHead = ListNode(-1)
dummyHead.next = head
pre = dummyHead
while pre.next:
if pre.val == pre.next.val:
pre.next = pre.next.next
else:
pre = pre.next
return head