原题
给定一个排序链表,删除所有重复的元素只留下原链表中没有重复的元素。
样例
给出 1->2->3->3->4->4->5->null,返回 1->2->5->null
给出 1->1->1->2->3->null,返回 2->3->null
解题思路
- 基础链表操作,与Remove Duplicates from Sorted List I的区别是如果有重复,重复的节点全部删除
- 因为头节点有被删除的可能,所以使用dummy node
完整代码
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def deleteDuplicates(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
DummyNode = ListNode(0)
DummyNode.next = head
current = DummyNode
while current.next != None and current.next.next != None:
if current.next.val == current.next.next.val:
temp = current.next.val
while current.next != None and current.next.val == temp:
current.next = current.next.next
else:
current = current.next
return DummyNode.next