Stay button algorithm --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.

Return a deep copy of the list.

 

Example 1:

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:

   Method a:
     use a hash table, the value corresponding to the node address list, make a copy of a main chain, and recording the node address of the new node value chain with the hash table corresponding to

     Then traverse the original list, the random list by the original value of a pointer, and the hash table to find the pointer to the new random chain corresponding to

    Cons: need extra space, and the node value can not be the same, otherwise the hash table fails

  Method Two:

    The new strand copied directly behind the main chain, then when the copy of random pointer, the new pointer value chain random random value back to the old chain

    The new chain is then spun off from the backbone

  

 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 };

 

  

Guess you like

Origin www.cnblogs.com/zzw1024/p/11809316.html