Copy List with Random Pointer

来源:互联网 发布:js代码注解 编辑:程序博客网 时间:2024/04/29 20: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.

题目要求返回的是深度拷贝,因此拷贝时必须重新申请空间。关于deep copy 和 shallow copy,可以参考http://blog.csdn.net/andrewseu/article/details/26852217

如果先建立节点再寻找每个节点的random指针,思路简单,但是时间复杂度为O(n^2),会超时。因此必须转换思维,先把新的节点查到旧节点的后面,这样相对关系就很明显,寻找random指针也很简单,并且时间复杂度为O(n)。不过要注意的一点是不要在寻找random指针的同时拆分链表,因为拆分链表破坏了链表的结构,如果有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:RandomListNode *copyRandomList(RandomListNode *head) {if (!head)return NULL;RandomListNode *copyHead=NULL,*copyCurrent=NULL;RandomListNode *current = head;while (current){if (current == head){copyHead = new RandomListNode(head->label);copyCurrent = copyHead;}else{RandomListNode *rNode = new RandomListNode(current->label);copyCurrent = rNode;}copyCurrent->next = current->next;current->next = copyCurrent;current = copyCurrent->next;}current = head;while (current){if (current->random){current->next->random = current->random->next;}current = current->next->next;}current = head;copyCurrent = copyHead;while (current){current->next = copyCurrent->next;current = current->next;if (!current)break;copyCurrent->next = current->next;copyCurrent = copyCurrent->next;}return copyHead;}};


0 0
原创粉丝点击