105. Copy List with Random Pointer

題目

https://www.lintcode.com/problem/copy-list-with-random-pointer/description?_from=ladder&&fromId=2

實現

  1. 先從頭到尾遍歷一次鏈表,並創建好所有的 ListNode,建立前後連接
  2. 遍歷的時候還要記錄 random 值,這裏的 random 值就指向原鏈表的節點
  3. 還要用一個 hash table 來記錄 {originListNode : copyListNode}
  4. 完成遍歷後,再遍歷 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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章