【題目】
一種特殊的鏈表節點類型描述如下:
class Node:
def __init__(self, data):
self.val = data
self.next = None
self.rand = None
Node類中的value是節點值,next指針和正常單鏈表中next指針的意義一樣,都指向下一個節點,rand指針是Node類中新增的指針,這個指針可能指向鏈表中的任意一個節點,也可能指向None。
給定一個由Node節點類型組成的無環單鏈表的頭節點head,請實現一個函數完成這個鏈表中所有結構的複製,並返回複製的新鏈表的頭節點。
進階:不使用額外的數據結構,只用有限幾個變量,且在時間複雜度爲O(N)內完成原問題要實現的函數。
【基本思路】
原問題。使用一個哈希表,建立舊節點和新節點的對應關係。然後遍歷一遍鏈表,根據原鏈表和哈希表設置每一個新節點的next和rand指針。
#python3.5
class RandNode:
def __init__(self, data):
self.val = data
self.next = None
self.rand = None
def copyListWithRand1(head):
if head == None:
return None
map = {}
cur = head
while cur != None:
map[cur] = RandNode(cur.val)
cur = cur.next
cur = head
while cur != None:
map[cur].next = None if cur.next == None else map[cur.next]
map[cur].rand = None if cur.rand == None else map[cur.rand]
cur = cur.next
return map[head]
進階問題。在原鏈表中每一個節點的後面插入一個副本節點。遍歷一遍鏈表,在遍歷時設置每一個副本節點的rand指針。最後再分離成兩個鏈表即可。
def copyListWithRand2(head):
if head == None:
return None
cur = head
while cur != None:
next = cur.next
cur.next = RandNode(cur.val)
cur.next.next = next
cur = next
cur = head
while cur != None:
cur.next.rand = None if cur.rand == None else cur.rand.next
cur = cur.next.next
copyHead = head.next
cur = head
while cur != None:
next = cur.next
cur.next = next.next
next.next = None if next.next == None else next.next.next
cur = cur.next
return copyHead