Copy List with Random Pointer
来源:互联网 发布:2016windows系统的手机 编辑:程序博客网 时间:2024/06/03 21:32
题目大意:求一个链表的深度拷贝,这个链表中的节点有两个指针,一个next指针指向它的下驱节点,另一个random指针可以指向空或者链表中任意的其他节点。
解题思路:分三步,
第一步顺序遍历链表,拷贝每个节点,将拷贝的节点插入到被拷贝节点的后面。
第二步,拷贝radom指针。
第三步,将拷贝节点分离出来。
#include <iostream>#include <cstdio>using namespace std;struct RandomListNode {int label;RandomListNode *next, *random;RandomListNode(int x) : label(x), next(NULL), random(NULL) {}};class Solution {public:RandomListNode *copyRandomList(RandomListNode *head) {copyNode(head);copyRandomNode(head);return separate(head);}private:void copyNode(RandomListNode *head) {RandomListNode *cur = head;while(cur != NULL) {RandomListNode *node = new RandomListNode(cur->label);node->next = cur->next;cur->next = node;cur = node->next;}}void copyRandomNode(RandomListNode *head) {RandomListNode *cur = head;RandomListNode *copy_cur = cur != NULL ? cur->next : NULL;while(cur != NULL && copy_cur != NULL) {copy_cur->random = cur->random != NULL ? cur->random->next : NULL;cur = copy_cur->next;copy_cur = cur != NULL ? cur->next : NULL;}}RandomListNode *separate(RandomListNode *head) {RandomListNode *cur = head;RandomListNode *copy_cur = cur != NULL ? cur->next : NULL;RandomListNode *copy_head = copy_cur;while(cur != NULL && copy_cur != NULL) {cur->next = copy_cur->next;cur = cur->next;copy_cur->next = cur != NULL ? cur->next : NULL;copy_cur = copy_cur->next;}return copy_head;}};
0 0
- Copy List with Random Pointer
- Copy List with Random Pointer
- Copy List with Random Pointer
- Copy List with Random Pointer
- Copy List with Random Pointer
- Copy List with Random Pointer
- Copy List with Random Pointer
- Copy List with Random Pointer
- Copy List with Random Pointer
- Copy List with Random Pointer
- Copy List with Random Pointer
- Copy List with Random Pointer
- Copy List with Random Pointer
- Copy List with Random Pointer
- Copy List with Random Pointer
- Copy List with Random Pointer
- Copy List with Random Pointer
- Copy List with Random Pointer
- [LeetCode] Nonrecursive postorder traversal 非递归后续遍历
- What is the difference between max-device-width and max-width for mobile web?
- python各种类型转换-int,str,char,float,ord,hex,oct等
- struts2 表单对象没有自动实例化
- failed to open stream: Permission denied in
- Copy List with Random Pointer
- 排名(杭电oj1236)(简单排序)
- What Is A CSS Reset?
- 026Java文件数据IO操作
- 如何取消WIN2008下应用报错后弹出的对话框
- [leetCode] Intersection of Two Linked Lists
- Ceilometer项目源码分析----ceilometer-alarm-notifier服务的初始化和启动
- #1066 : 无间道之并查集
- #1051 : 补提交卡