[leetcode] Copy List with Random Pointer
来源:互联网 发布:bit.edu.cn哪个是域名 编辑:程序博客网 时间:2024/05/03 20:30
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.
思路:先在原节点的后面复制前一个节点,这样的话原节点p->random就可以通过p->next->random=p->random->next进行复制,最后拆分节点就得到了复制的list
代码:
/** * 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: RandomListNode *copyRandomList(RandomListNode *head) { if(head==NULL) return NULL; RandomListNode *res; RandomListNode *temp=head,*temp2=head->next; while(temp!=NULL){ temp->next=new RandomListNode(temp->label); temp->next->next=temp2; temp=temp2; if(temp2!=NULL){ temp2=temp2->next; } } temp=head; temp2=head->next; while(temp!=NULL){ if(temp->random!=NULL){ if(temp->next!=NULL) temp2->random=temp->random->next; } if(temp->random==NULL){ temp2->random=NULL; } temp=temp->next->next; if(temp2->next!=NULL){ temp2=temp2->next->next; } } res=head->next; temp=head; temp2=head->next; while(temp2->next!=NULL){ temp->next=temp2->next; temp=temp2; if(temp2->next!=NULL){ temp2=temp2->next; } } temp->next=NULL; temp2->next=NULL; return res; }};
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
- getApplicationContext()、Activity.this、 getBaseContext区别
- 【计算机视觉】对象距离的平面显示
- myEclipse10.6整合struts2.1+spring3.0+hibernate3.3(很好的文章,图片没上传)
- OC对象内存管理
- tomcat6源码分析二(初始化和启动流程)
- [leetcode] Copy List with Random Pointer
- 警方根据房间房管局发达国家梵蒂冈就
- 发国家的法规军阀割据东方国际法国际分工
- 过好几个好看共和国换个好看好看
- 几种线程池的实现算法分析
- 卡特兰数
- 共和国呵呵黄金客户即可
- 火炬计划进口环节考核进口环节
- 《PHP和MySQL Web应用开发》笔记