16. Copy List with Random Pointer

类同:剑指 Offer 题目汇总索引第26题

Copy List with Random Pointer

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.

说明:分三步, 1. 每个节点复制其本身并链接在后面。 2, 复制随机指针。 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) {
if(head == NULL) return NULL;
RandomListNode *head2, *p, *p2;
p = head2 = head;
while(p) {
RandomListNode *s = new RandomListNode(p->label);
s->next = p->next;
p->next = s;
p = s->next;
}
p = head;
while(p) {
if(p->random) p->next->random = p->random->next;
p = p->next->next;
}
head2 = p2 = head->next; p = head;
while(p) {
p->next = p->next->next;
p = p->next;
if(p2->next) {
p2->next = p2->next->next;
p2 = p2->next;
}
}
return head2;
}
};
上一篇:ES6-函数参数的默认值


下一篇:ES6之数组的Array.from()方法