题目描述:
请实现 copyRandomList 函数,复制一个复杂链表。在复杂链表中,每个节点除了有一个 next 指针指向下一个节点,还有一个 random 指针指向链表中的任意节点或者 null。
示例1:
输入:head = [[7,null],[13,0],[11,4],[10,2],[1,0]]
输出:[[7,null],[13,0],[11,4],[10,2],[1,0]]
示例2:
输入:head = [[1,1],[2,1]]
输出:[[1,1],[2,1]]
示例3:
输入:head = [[3,null],[3,0],[3,null]]
输出:[[3,null],[3,0],[3,null]]
示例4:
输入:head = []
输出:[]
解释:给定的链表为空(空指针),因此返回 null。
解题思路:
1、利用hashMap:
这里的难点是如何找到结点的随机random
指针,如何按照常规的查找方法从head
节点开始查找,那么每一个节点时候都要遍历一遍链表,这样时间复杂度为O(n^2)
。可以使用一个hashMap
将所有节点存储起来,这样就可以保存其random
指针信息(因为random
指针说白了也就是链表中一个普通的节点),最后就可以通过hashMap
取出其random
节点。这样的时间复杂度为O(n)
。
2、三步走:
上述解法的时间复杂度为O(n)
,但是借助了一个hashMap
,下面介绍一种没有借助hashMap
且时间复杂度为O(n)
的解法,简单来说,分为三步:(1)复制每一个节点,使得复制后的节点都在当前节点的下一个节点;(2)原生链表的节点的指向任意节点,使复制的节点也都指向某一任意节点;(3)重新连接节点,把原生节点重新连接起来,把克隆后的节点连接起来(即将链表拆分为原链表和复制链表),最后返回复制链表。
以上过程可以用下图表示:
注: 以上解法参考于LeetCode中Markus大佬的题解
实现代码:
//解法1:使用hashMap
public Node copyRandomList(Node head) {
HashMap<Node,Node> map = new HashMap<>();
Node cur = head;
while(cur != null){
map.put(cur, new Node(cur.val));
cur = cur.next;
}
cur = head;
while(cur != null){
map.get(cur).next = map.get(cur.next);
map.get(cur).random = map.get(cur.random);
cur = cur.next;
}
return map.get(head);
}
//解法2
public Node copyRandomList1(Node head) {
if(head == null)
return head;
Node cur = head;
//第一步:拷贝链表
while(cur != null){
Node next = cur.next;
Node clone = new Node(cur.val);
cur.next = clone;
clone.next = next;
cur = clone.next;
}
cur = head;
//第二步:连接复制节点的随机节点
while(cur != null){
Node clone = cur.next;
clone.random = cur.random != null ? cur.random.next : null;
cur = clone.next;
}
cur = head;
//第三步:拆分成原链表和复制链表
Node res = head.next;
while(cur != null){
Node clone = cur.next;
cur.next = clone.next;
clone.next = cur.next != null ? cur.next.next : null;
cur = cur.next;
}
return res;
}