Chain Table Style
Usually a linked list is a value, a next pointer, pointing to the back node.
The structure is as follows:
struct Node{int val;struct node* next;}
There is a pointer to the node in this topic, in addition to the next pointer to a node below, and a random pointer to a randomly-linked list of nodes.
The structure is as follows:
struct Node{int val;struct node* next;struct node* Random;}
Normal linked list value copy
Usually when we copy a linked list, we make a copy of the value, and only use it from the beginning, because the relationship between the nodes and the nodes has been determined, and each node points to the back node. It is possible to traverse the copy directly.
Random pointer linked list copy
A copy of a random list is a copy of the link between the node and the node.
O (n^2) method does not write, is to go through the first time, each traversal in the list of random points to the node.
The following is an O (n) method, which is to create the nodes sequentially, and each node is inserted at the end of the original linked list. For example, a linked list would be:
1 -> 2 -> 3 -> 4 -> 5 -> NULL (随机指针没有表示出来,因为不好画)
Become:
1->1‘->2->2‘->3->3‘->4->4‘->5->5‘->NULL (新插入的节点都加了单引号来区分)
So we find that if1
The random pointer points to the node3
, then we let1‘
The random pointer points to the3
Behind the3‘
Because we can get through it.1->random
Directly to access3
, so directly let1‘->random = 1->random->next
You can do it. So the copy was successful.
The last time to put this new list out again ~ is to let it 1‘->next = 1‘->next->next
.
The code is as follows:
#include <iostream>using namespace std;struct randomlistnode{int label; Randomlistnode *next, *random; Randomlistnode (int x): label (x), Next (null), random (null) {}};class Solution{public:randomlistnode * copyrandomlist (Ra Ndomlistnode *head) {Randomlistnode *node; Randomlistnode *loop = head; if (loop = = null) {return null; } while (Loop! = NULL) {node = (randomlistnode*) malloc (sizeof (struct randomlistnode)); Node->label = loop->label; Node->next = loop->next; Node->random = NULL; Loop->next = node; loop = node->next; } loop = head; while (loop! = null) {if (loop->random! = null) {Loop->next->random = Loop->random ->next; } loop = loop->next->next; } Randomlistnode *copy = head->next; loop = head; node = Head->nExt while (loop! = NULL && Node->next! = null) {Loop->next = loop->next->next; Node->next = node->next->next; loop = loop->next; node = node->next; } loop->next = NULL; return copy; } };
Leetcode-copy List with Random pointer