【LeetCode】Copy List with Random Pointer
来源:互联网 发布:刷q币软件 编辑:程序博客网 时间:2024/05/16 17:49
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.
思路:总共分为三个函数来解决,可以参照《剑指offer》4.4的26题。
①先复制所有的节点,把复制的节点直接挂到原始节点后面,所以每两个节点值就是一样的;
②然后将复制的节点的random指针指点前驱节点的random指针指向的下一个节点;
③拆分链表成两个。
/** * Definition for singly-linked list with a random pointer. * struct RandomListNode { * int label; * RandomListNode *next, *random; * RandomListNode(int x) : label(x), next(NULL), random(NULL) {} * }; */class Solution {public: void CloneList(RandomListNode *head){ RandomListNode *pNode=head; while(pNode!=NULL){ RandomListNode* tmp=new RandomListNode(pNode->label); //tmp->label=pNode->label; tmp->next=pNode->next; tmp->random=NULL; pNode->next=tmp; pNode=tmp->next; } } void CloneRandom(RandomListNode *head){ RandomListNode *pNodeold=head; while(pNodeold!=NULL){ if(pNodeold->random!=NULL){ pNodeold->next->random=pNodeold->random->next; } pNodeold=pNodeold->next->next; } } RandomListNode *DevideList(RandomListNode *head){ RandomListNode *pNodeold=head; RandomListNode *headnew=NULL; RandomListNode *pNodenew=NULL; if(pNodeold!=NULL){ headnew=pNodenew=head->next; pNodeold->next=pNodenew->next; pNodeold=pNodeold->next; } while(pNodeold!=NULL){ pNodenew->next=pNodeold->next; pNodenew=pNodenew->next; pNodeold->next=pNodenew->next; pNodeold=pNodeold->next; } return headnew; } RandomListNode *copyRandomList(RandomListNode *head) { if(head==NULL)return NULL; CloneList(head); CloneRandom(head); return DevideList(head); }};
0 0
- [leetcode][list] Copy List with Random Pointer
- Leetcode: Copy List with Random Pointer
- LeetCode: Copy List with Random Pointer
- [LeetCode] Copy List with Random Pointer
- [leetcode]Copy List with Random Pointer
- LeetCode:Copy List with Random Pointer
- leetcode Copy List with Random Pointer
- LeetCode:Copy List with Random Pointer
- LeetCode题解:Copy List with Random Pointer
- [LeetCode]Copy List with Random Pointer
- leetcode Copy List with Random Pointer
- leetcode-Copy List with Random Pointer
- Leetcode: Copy List with Random Pointer
- LeetCode | Copy List with Random Pointer
- [LeetCode] Copy List with Random Pointer
- LeetCode OJ:Copy List with Random Pointer
- LeetCode(138)Copy List with Random Pointer
- [LeetCode] - Copy List with Random Pointer
- 九度oj 1120全排列
- x^y % m 大数
- POJ-1005 I Think I Need a Houseboat
- main函数执行之前都干啥了----C/C++运行时库剖析
- begin
- 【LeetCode】Copy List with Random Pointer
- 常见基本计算
- 工作6年后的我
- 3.1操作系统之存储管理
- C++primer plus第六版课后编程题答案13.4
- 模拟新浪微博的随便看看栏目
- ZOJ-2540
- Spring IOC容器
- J2ee和.net心得