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指针解决引用。
第三趟,将链表拆开。
在leetcode上实际执行时间为120ms。
/** * 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 fake(0); RandomListNode *p = &fake; while (head) { p->next = head; head = head->next; p->next->next = new RandomListNode(p->next->label); p = p->next->next; } p = fake.next; while (p) { if (p->random) { p->next->random = p->random->next; } p = p->next->next; } RandomListNode fake2(0); head = &fake2; p = fake.next; while (p) { head->next = p->next; head = head->next; p->next = p->next->next; p = p->next; } return fake2.next; } };
Copy List with Random Pointer -- leetcode
原文地址:http://blog.csdn.net/elton_xiao/article/details/46301981