力扣算法——138CopyListWithRandomPointer【M】

A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.node

Return a deep copy of the list.dom

 

Example 1:spa

Input:
{"$id":"1","next":{"$id":"2","next":null,"random":{"$ref":"2"},"val":2},"random":{"$ref":"2"},"val":1}

Explanation:
Node 1's value is 1, both of its next and random pointer points to Node 2.
Node 2's value is 2, its next pointer points to null and its random pointer points to itself.

 

Note:指針

  1. You must return the copy of the given head as a reference to the cloned list.

Solution:code

   方法一:
     使用哈希表,將鏈表值與節點地址對應,先複製一條主鏈,並用哈希表記錄新鏈的節點值與節點地址的對應blog

     而後遍歷原鏈表,經過原鏈表隨機指針的值,和哈希表,來找到新鏈所對應的隨機指針ip

    缺點:須要額外的空間,而且節點值不能相同,不然哈希表失效get

  方法二:input

    將新鏈直接複製在主鏈後面,那麼當複製隨機指針時,新鏈的隨機指針值就在舊鏈的隨機值後面it

    而後將新鏈從主鏈中脫離出來

  

 1 class Solution {
 2 public:
 3     RandomListNode *copyRandomList(RandomListNode *head) {
 4         RandomListNode* p = head;
 5         while (p != nullptr)
 6         {
 7             RandomListNode* q = new RandomListNode(p->label);
 8             q->next = p->next;
 9             p->next = q;
10             p = p->next->next;
11         }
12         p = head;
13         while (p != nullptr)
14         {
15             if (p->random != nullptr)
16                 p->next->random = p->random->next;
17             p = p->next->next;
18         }
19         p = head;
20         RandomListNode *resHead = new RandomListNode(-1), *q;
21         q = resHead;
22         while (p != nullptr)
23         {
24             q->next = p->next;
25             q = q->next;
26             p->next = p->next->next;
27             p = p->next;
28         }
29         return resHead->next;
30     }
31 };
相關文章
相關標籤/搜索