copy a random link
生活随笔
收集整理的這篇文章主要介紹了
copy a random link
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
題目: 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. 1 /**
2 * Definition for singly-linked list with a random pointer.
3 * struct RandomListNode {
4 * int label;
5 * RandomListNode *next, *random;
6 * RandomListNode(int x) : label(x), next(NULL), random(NULL) {}
7 * };
8 */
9 class Solution {
10 public:
11 RandomListNode *copyRandomList(RandomListNode *head) {
12 if(head == NULL) return NULL;
13 //將新節(jié)點復(fù)制到原來節(jié)點后面
14 RandomListNode *copy;
15 RandomListNode *p = head;
16 RandomListNode *tmp;
17 while(p!=NULL)
18 {
19 copy = new RandomListNode(p->label);
20 tmp = p->next;
21 p->next = copy;
22 copy->next = tmp;
23 p = tmp;
24 }
25 //將新結(jié)點與隨機結(jié)點相連接
26 p = head;
27 copy = head->next;
28 while(p!=NULL && copy!=NULL)
29 {
30 copy->random = ((p->random)?p->random->next:NULL);
31 p = ((copy->next)?copy->next:NULL);
32 copy = ((p->next)?p->next:NULL);
33 }
34 //將新節(jié)點與原結(jié)點拆開
35 p = head;
36 head = copy = head->next;
37 while(p!=NULL && copy!=NULL)
38 {
39 p->next = ((copy->next)?copy->next:NULL);
40 p = ((p->next)?p->next:NULL);
41 copy->next = ((p)?p->next:NULL);
42 copy = ((copy->next)?copy->next:NULL);
43 }
44 return head;
45 }
46 };
?
轉(zhuǎn)載于:https://www.cnblogs.com/dzy521/p/9144690.html
總結(jié)
以上是生活随笔為你收集整理的copy a random link的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 是否同一棵二叉搜索树
- 下一篇: JS数组的需要注意的问题