题目
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指针。
- 可以先生成一个random指针均为NULL的新链表,并保存链表对应位置新旧链表指针的一一映射关系(map),则第二次遍历新链表时可以为所有的random指针赋值。
Coding
/**
* 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;
// new list head
RandomListNode* newHead = new RandomListNode(head->label);
map<RandomListNode*, RandomListNode*> MapListNode;
MapListNode[head] = newHead;
// new list node
RandomListNode* oldNode = head->next;
RandomListNode* tempNode = newHead;
// generate new list
while (oldNode) {
RandomListNode* newNode = new RandomListNode(oldNode->label);
tempNode->next = newNode;
MapListNode[oldNode] = newNode;
oldNode = oldNode->next;
tempNode = newNode;
}
// assign random pointer value
tempNode = newHead;
oldNode = head;
while (oldNode && tempNode) {
if (oldNode->random) {
tempNode->random = MapListNode[oldNode->random];
}
oldNode = oldNode->next;
tempNode = tempNode->next;
}
return newHead;
}
};
拓展
参考:http://blog.youkuaiyun.com/litoupu/article/details/41623807
技巧:直接在原有链表上进行操作,每个结点后都new一个新的同值结点并连接。第二次再将random值通过random->next赋值。最后分离出原有链表和新链表。