题目连接:Leetcode 138 Copy List with Random Pointer
解题思路:首先遍历一遍链表,为每个结点新建一个拷贝,并将对应label和指针关系保存在map中。然后再遍历一遍数组,更新每个新结点的random和next指针。
/**
* 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;
map<int, RandomListNode *> graph;
RandomListNode* mov = head;
while (mov != NULL) {
graph[mov->label] = new RandomListNode(mov->label);
mov = mov->next;
}
RandomListNode* first = graph[head->label];
mov = first;
while (head != NULL) {
mov->next = (head->next == NULL ? NULL : graph[head->next->label]);
mov->random = (head->random == NULL ? NULL : graph[head->random->label]);
mov = mov->next;
head = head->next;
}
return first;
}
};