[leetcode]Copy List with Random Pointer @ Python


原題地址:https://oj.leetcode.com/problems/copy-list-with-random-pointer/

題意:

A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.

Return a deep copy of the list.

解題思路:這題主要是需要深拷貝。看圖就明白怎么寫程序了。

 

首先,在原鏈表的每個節點后面都插入一個新節點,新節點的內容和前面的節點一樣。比如上圖,1后面插入1,2后面插入2,依次類推。

其次,原鏈表中的random指針如何映射呢?比如上圖中,1節點的random指針指向3,4節點的random指針指向2。如果有一個tmp指針指向1(藍色),則一條語句:tmp.next.random = tmp.random.next;就可以解決這個問題。

第三步,將新的鏈表從上圖這樣的鏈表中拆分出來。

代碼:

# Definition for singly-linked list with a random pointer.
# class RandomListNode:
#     def __init__(self, x):
#         self.label = x
#         self.next = None
#         self.random = None

class Solution:
    # @param head, a RandomListNode
    # @return a RandomListNode
    def copyRandomList(self, head):
        if head == None: return None
        tmp = head
        while tmp:
            newNode = RandomListNode(tmp.label)
            newNode.next = tmp.next
            tmp.next = newNode
            tmp = tmp.next.next
        tmp = head
        while tmp:
            if tmp.random:
                tmp.next.random = tmp.random.next
            tmp = tmp.next.next
        newhead = head.next
        pold = head
        pnew = newhead
        while pnew.next:
            pold.next = pnew.next
            pold = pold.next
            pnew.next = pold.next
            pnew = pnew.next
        pold.next = None
        pnew.next = None
        return newhead

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM