1. 程式人生 > >Leetcode 138:複製帶隨機指標的連結串列(超詳細的解法!!!)

Leetcode 138:複製帶隨機指標的連結串列(超詳細的解法!!!)

給定一個連結串列,每個節點包含一個額外增加的隨機指標,該指標可以指向連結串列中的任何節點或空節點。

要求返回這個連結串列的深度拷貝。

解題思路

這個問題其實挺難的,關鍵問題就在於這個random指標。我們看這樣的例子

我們可以這樣去做

首先遍歷連結串列,然後將節點複製新增到原節點後。

接著再遍歷一遍連結串列,這一次的遍歷我們複製random指標。

最後我們將連結串列還原回去。程式碼如下:
class Solution(object):
    def copyRandomList
(self, head): """ :type head: RandomListNode :rtype: RandomListNode """ if not head: return None h1, h2, h = head, head, head while h1: node = RandomListNode(h1.label) node.next = h1.next h1.
next = node h1 = node.next while h2: if h2.random: h2.next.random = h2.random.next h2 = h2.next.next res = h.next while h: tmp = h.next h.next = tmp.next if h.next
: tmp.next = h.next.next h = h.next return res

我將該問題的其他語言版本新增到了我的GitHub Leetcode

如有問題,希望大家指出!!!