Leetcode Copy List with Random Pointer
来源:互联网 发布:java 形参 实参 编辑:程序博客网 时间:2024/06/03 04:36
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.
最先想到就是遍历列表生成新的列表,但没有对random域进行赋值。在遍历一次列表,然后进行random域赋值。但其存在一个问题,就是进行random赋值的时候需要耗费时间久,因为random域没有规律可循,需要进行遍历列表,也就是时间复杂度为O(N^2)。后面发现一个方法,就是通过对每个列表节点进行double,然后在进行random域的复制就变得有规律可循:
1.将列表内的节点全部复制,并连接在原节点后面
2.对新的节点的random域进行赋值,新节点.random = 原节点.random.next
3.将新节点从列表中抽离出新的列表
代码如下:
/** * 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) { RandomListNode* next,*cur; cur = head; while(cur) { next = cur->next; RandomListNode* tmp = new RandomListNode(cur->label); tmp->next = next; cur->next = tmp; cur = next; } cur = head; while(cur) { next = cur->next; if(cur->random) next->random = cur->random->next; else next->random = cur->random; cur = next->next; } RandomListNode* result = new RandomListNode(0); RandomListNode* copy,*copyCur=result; cur = head; while(cur) { next = cur->next->next; copyCur->next = cur->next; copyCur = copyCur->next; cur->next = next; cur = cur->next; } return result->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
- mycat的入门教程(二)
- Redis-pipeline
- centos7离线安装docker
- http://www.cnblogs.com/yzuzhang/p/4763606.html
- 《Python简明教程》一
- Leetcode Copy List with Random Pointer
- 三、kafka的github源码
- java.util.concurrent 之BlockingQueue
- 水题 第三站 How many prime numbers
- spring过滤器和拦截器的区别和联系
- 判断有向图是否存在环、环的个数、环的元素
- Java工程师成长路线
- 南阳OJ 47 过河问题
- Jquery+ashx实现Ajax