分類(lèi):LinkedList
考察知識(shí)點(diǎn):LinkedList
最優(yōu)解時(shí)間復(fù)雜度:**O(n) **
82. Remove Duplicates from Sorted List II
Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
Example 1:
Input: 1->2->3->3->4->4->5
Output: 1->2->5
Example 2:
Input: 1->1->1->2->3
Output: 2->3
代碼:
方法:
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def deleteDuplicates(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if head==None or head.next==None:
return head
dummy=ListNode(0)
dummy.next=head
p=dummy
#后來(lái)都存在的時(shí)候
while p.next and p.next.next:
#標(biāo)注后來(lái)的數(shù),并且刪除
if p.next.val==p.next.next.val:
samenum=p.next.val
while(p.next!=None and p.next.val==samenum):
p.next=p.next.next
else:
p=p.next
return dummy.next
討論:
1.一開(kāi)始總以為自己很聰明結(jié)果發(fā)現(xiàn)自己其實(shí)做不好這個(gè)題目,就那么做吧,多練習(xí)應(yīng)該就會(huì)好的

還是大佬的方法好用