File tree 1 file changed +31
-0
lines changed
1 file changed +31
-0
lines changed Original file line number Diff line number Diff line change
1
+ // 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.
2
+ // Return a deep copy of the list.
3
+ /* *
4
+ * Definition for singly-linked list with a random pointer.
5
+ * struct RandomListNode {
6
+ * int label;
7
+ * RandomListNode *next, *random;
8
+ * RandomListNode(int x) : label(x), next(NULL), random(NULL) {}
9
+ * };
10
+ */
11
+ class Solution {
12
+ public:
13
+ RandomListNode *copyRandomList (RandomListNode *head) {
14
+ RandomListNode *copy,*p;
15
+ if (!head) return NULL ;
16
+ for (p=head;p;p=p->next ){
17
+ copy = new RandomListNode (p->label );
18
+ copy->next = p->next ; // insert new at old next
19
+ p = p->next = copy;
20
+ }
21
+ for (p=head;p;p=copy->next ){
22
+ copy = p->next ; // copy random point
23
+ copy->random = (p->random ?p->random ->next :NULL );
24
+ }
25
+ for (p=head,head=copy=p->next ;p;){
26
+ p = p->next = copy->next ; // split list
27
+ copy = copy->next = (p?p->next :NULL );
28
+ }
29
+ return head;
30
+ }
31
+ };
You can’t perform that action at this time.
0 commit comments