问题:
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.
解决:
【题意】深拷贝一个链表,链表除了含有next指针外,还包含一个random指针,该指针指向字符串中的某个节点或者为空。
① 难点就在于如何处理随机指针的问题,用Hash map来缩短查找时间,HashMap的key存原始pointer,value存新的pointer。第一遍遍历生成所有新节点时同时建立一个原节点和新节点的哈希表,第二遍给随机指针赋值时,查找时间是常数级。时间复杂度O(n),空间复杂度O(n)。
假设原始链表如下,细线表示next指针,粗线表示random指针,没有画出的指针均指向NULL:
/**
* 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 {//4ms
public RandomListNode copyRandomList(RandomListNode head) {
if (head == null) {
return null;
}
Map<RandomListNode,RandomListNode> map = new HashMap<>();
RandomListNode res = new RandomListNode(head.label);//复制节点
RandomListNode node = res;
RandomListNode cur = head.next;
map.put(head,res);//key为旧节点,value为新节点
while(cur != null){ //依次创建新的节点并将它们连接起来
RandomListNode tmp = new RandomListNode(cur.label);
node.next = tmp;
map.put(cur,tmp);
node = node.next;
cur = cur.next;
}
node = res;
cur = head;
while(node != null){
node.random = map.get(cur.random);//因为第一遍已经把链表复制好了并且也存在HashMap里了,所以只需从HashMap中,把当前旧的cur.random作为key值,得到新的value的值,并把其赋给新node.random就好。
node = node.next;
cur = cur.next;
}
return res;
}
}
② 使用另一种方法,可以分为以下三个步骤:
1. 在原链表的每个节点后面拷贝出一个新的节点
2. 依次给新的节点的随机指针赋值,而且这个赋值非常容易 cur->next->random = cur->random->next
3. 断开链表可得到深度拷贝后的新链表
public class Solution {//2ms
public RandomListNode copyRandomList(RandomListNode head) {
if (head == null) {
return null;
}
RandomListNode cur = head;
while(cur != null){
RandomListNode node = new RandomListNode(cur.label);//复制节点
node.next = cur.next;
cur.next = node;
cur = node.next;
}
cur = head;
while(cur != null){//为节点赋random值
if(cur.random != null){
cur.next.random = cur.random.next;
}
cur = cur.next.next;
}
cur = head;
RandomListNode res = head.next;
while(cur != null){//断开连接,得到复制的链表
RandomListNode tmp = cur.next;
cur.next = tmp.next;
if (tmp.next != null) {
tmp.next = tmp.next.next;
}
cur = cur.next;
}
return res;
}
}