Copy List with Random Pointer
Question
A linked list is given such that each node contains an additional random pointer that could point to any node in the list or null.
Return a deep copy of the list.
*Difficulty: Hard, Frequency: High
https://leetcode.com/problems/copy-list-with-random-pointer/
My Solution
看了一下提示搞出来的,其实大概的意思就是,用一个map来记住原来的liskedlist的每个node对应着新建linkedlist(deepcopy)的哪个node。<之后书上的另一个方法其实也是这个意思,只不过通过改linkedlist结构节省map的空间而已,本质上没太大区别>
/**
* 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) {
Map<RandomListNode, RandomListNode> map = new HashMap<>();
RandomListNode p = head;
RandomListNode dummyHead = new RandomListNode(0);
RandomListNode q = dummyHead;
while(p != null){
q.next = new RandomListNode(p.label);
map.put(p, q.next);
p = p.next;
q = q.next;
}
p = head;
q = dummyHead;
while(p != null){
q.next.random = map.get(p.random);
p = p.next;
q = q.next;
}
return dummyHead.next;
}
}
To be continued, 回去再看一下直接把copy的node加在原node后面变成一个双倍长度的linkedlist再去掉之前的node的方法…