題目
https://www.lintcode.com/problem/copy-list-with-random-pointer/description?_from=ladder&&fromId=2
實現
- 先從頭到尾遍歷一次鏈表,並創建好所有的 ListNode,建立前後連接
- 遍歷的時候還要記錄 random 值,這裏的 random 值就指向原鏈表的節點
- 還要用一個 hash table 來記錄
{originListNode : copyListNode}
- 完成遍歷後,再遍歷 copy 後的鏈表,根據 hash table 將 random 指向 copy 的節點
代碼
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):
# Define iteration reference
current = head
copy = RandomListNode(head.label)
copy_head = copy
current_head = head
# Init hash table
hash_table = {current: copy}
while current is not None:
copy.random = current.random
# Update next
if current.next is not None:
copy.next = RandomListNode(current.next.label)
hash_table[current.next] = copy.next
else:
copy.next = None
current = current.next
copy = copy.next
copy = copy_head
while copy is not None:
if copy.random is not None:
copy.random = hash_table[copy.random]
current_head = current_head.next
copy = copy.next
return copy_head