问题描述:
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.
分析:这题和clone graph可以说是异曲同工,同样使用一个map来对旧的节点与新的节点进行映射。然后再遍历一遍list,获取对应的新的节点图。
代码如下:440ms
/**
* Definition for singly-linked list with a random pointer.
* class RandomListNode {
* int label;
* RandomListNode next, random;
* RandomListNode(int x) { this.label = x; }
* };
*/
public class Solution {
public RandomListNode copyRandomList(RandomListNode head) {
HashMap<RandomListNode,RandomListNode> maps = new HashMap<>();
Queue<RandomListNode> queue = new LinkedList<>();
RandomListNode curNode = head;
while (curNode!=null){
maps.put(curNode,new RandomListNode(curNode.label));
curNode = curNode.next;
}
curNode = head;
while(curNode!=null){
maps.get(curNode).next = maps.get(curNode.next);
if(curNode.random!=null)
maps.get(curNode).random = maps.get(curNode.random);
else
maps.get(curNode).random = null;
curNode = curNode.next;
}
return maps.get(head);
}
}
补充:看到下面一张图,突然觉得太奇妙了
首先,要经过三次遍历,第一次遍历,将新节点插入到原有的list中
第二次遍历,利用如下公式,生成random信息
newNode ->random = oldNode->random->next;
第三次遍历,将原有的链表分开为两个链表。
代码如下:128ms
/**
* 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;
RandomListNode *curNode = head;
RandomListNode *nextNode;
while (curNode) {
nextNode = curNode->next;
RandomListNode *newNode = new RandomListNode(curNode->label);
curNode->next = newNode;
newNode->next = nextNode;
curNode = nextNode;
}
//deal with the random list
curNode = head;
while(curNode && curNode->next){
if(curNode->random)
curNode->next->random = curNode->random->next;
curNode = curNode->next->next;
}
RandomListNode *newHead = head->next;
curNode = head;
//恢复oldlist and newList
while (curNode && curNode->next != NULL) {
nextNode = curNode->next;
curNode->next = nextNode->next;
curNode = nextNode;
}
return newHead;
}
};