Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
For example,
Given 1->2->3->3->4->4->5, return 1->2->5.
Given 1->1->1->2->3, return 2->3.
题意:类似83移除重复结点,只是83中删除重复的结点,保留一个,此题中只要重复的结点都删除,只保留单个的结点
p.next始终指向需要判断的元素,需要两个while循环,注意判断条件,其中一个用来过滤重复结点
不同于83,需要判断,若无重复结点,p=p.next,若有重复结点,则p.next指向重复结点后一结点
Runtime: 56 ms
# 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):
dummy=ListNode(0)
dummy.next=head
p=dummy
while p.next and p.next.next:
p1=p.next
while p1.val==p1.next.val:
p1=p1.next
if not p1.next:
break
if p.next==p1:
p=p.next
else:
p.next=p1.next
return dummy.next