leetcode Copy List with Random Pointer
来源:互联网 发布:如何淘宝开企业店铺 编辑:程序博客网 时间:2024/05/19 03:20
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.
首先需要理解的是深拷贝是什么意思吧。深拷贝不只是单纯的换个名字,而是要重新构造,结构一样。看这个图就能理解这个算法的精髓了/** * 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) {} * }; */ /* 该算法更为巧妙,不用保存原始链表的映射关系,构建新节点时,指针做如下变化,即把新节点插入到相应的旧节点后面:1、构建新节点random指针:new1->random = old1->random->next, new2-random = NULL, new3-random = NULL, new4->random = old4->random->next2、恢复原始链表以及构建新链表:例如old1->next = old1->next->next, new1->next = new1->next->next该算法时间复杂度O(N),空间复杂度O(1)*/class Solution {public: RandomListNode *copyRandomList(RandomListNode *head) { if(head==NULL) return NULL; RandomListNode *old=head; while(old!=NULL){ RandomListNode *add=new RandomListNode(old->label); RandomListNode *temp=old->next; old->next=add; add->next=temp; old=temp; } old=head; while(old!=NULL){ if(old->random!=NULL){ old->next->random=old->random->next; } old=old->next->next; } RandomListNode *dummy=new RandomListNode(INT_MIN); dummy->next=head; RandomListNode *n=dummy; old=head; while(old!=NULL){ n->next=n->next->next; old->next=old->next->next; old=old->next; n=n->next; } n->next=NULL; return dummy->next; }};
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
- PAT 1083. List Grades (25)
- C945 y系列三极管的管教排序EBC 电接触液位控制器UDK-201
- 如何定义全局变量
- 还原HP的F系快捷键,取消fn
- 【线段树】 HDOJ 4521 小明系列问题——小明序列
- leetcode Copy List with Random Pointer
- Java程序员应该知道的10个面向对象理论
- 14天学会安卓开发(第十一天)Android图形技术
- 一天一个小工具---读取Word文档
- [转]Redis作为消息队列与RabbitMQ的性能对比
- 有一个由大小写组成的字符串,现在需要对他进行修改,将其中的所有小写字母排在大写字母的前面
- How Tomcat works 之 StandardWrapper 标准包装
- cocos2d-x入门——场景显示分析
- java 多线程学习笔记1