[LinkedList]082 Remove Duplicates from Sorted List II

  • 分類(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ì)好的

還是大佬的方法好用
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容