題目
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.csdn.net/litoupu/article/details/41623807
技巧:直接在原有鏈表上進行操作,每個結點後都new一個新的同值結點並連接。第二次再將random值通過random->next賦值。最後分離出原有鏈表和新鏈表。