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.
分析:
见《剑指offer》面试题:26 复杂链表的复制。
/**
* 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) {
for (RandomListNode *cur = head; cur;) {
RandomListNode *node = new RandomListNode(cur->label);
node->next = cur->next;
cur->next = node;
cur = node->next;
}
for (RandomListNode *cur = head; cur;) {
if (cur->random)
cur->next->random = cur->random->next;
cur = cur->next->next;
}
// 分拆两个单链表
RandomListNode dummy(-1);
for (RandomListNode *cur = head, *new_cur = &dummy; cur;) {
new_cur->next = cur->next;
cur->next = cur->next->next;
new_cur = new_cur->next;
cur = cur->next;
}
return dummy.next;
}
};