python解決複雜鏈表的複製

來源:互聯網
上載者:User

標籤:none   solution   span   com   enc   style   lis   參數   思路   

題目如下:輸入一個複雜鏈表(每個節點中有節點值,以及兩個指標,一個指向下一個節點,另一個特殊指標指向任意一個節點),返回結果為複製後複雜鏈表的head。(注意,輸出結果中請不要返回參數中的節點引用,否則判題程式會直接返回空)

思路:第一步在原鏈表的基礎上複製節點,將節點複製在原節點的後面。第二步複製隨機節點。 第三步將新舊鏈表分離。 圖示如下

代碼如下:

#encoding:utf8class  RandomListNode():    def __init__(self,x):        self.label = x        self.next = None        self.random = Noneclass Solution:    def clone(pHead):        if pHead == None:            return None        #複製節點在原節點之後        pCur = pHead        while(pCur != None):            node = RandomListNode(pCur.label)            node.next = pCur.next            pCur.next = node            pCur = node.next        #複製random節點        pCur = pHead        while(pCur != None):            if pCur.random != None:                pCur.next.random = pCur.random.next            pCur = pCur.next.next        head = pHead.next        cur = head        #將新舊鏈表分離        pCur = pHead        while(pCur != None):            pCur.next = pCur.next.next            if cur.next != None:                cur.next = cur.next.next            cur = cur.next            pCur = pCur.next        return head

 

python解決複雜鏈表的複製

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.