Leetcode 138:複製帶隨機指標的連結串列(超詳細的解法!!!)
阿新 • • 發佈:2019-01-09
給定一個連結串列,每個節點包含一個額外增加的隨機指標,該指標可以指向連結串列中的任何節點或空節點。
要求返回這個連結串列的深度拷貝。
解題思路
這個問題其實挺難的,關鍵問題就在於這個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
如有問題,希望大家指出!!!