请实现 copyRandomList 函数,复制一个复杂链表。在复杂链表中,每个节点除了有一个 next 指针指向下一个节点,还有一个 random 指针指向链表中的任意节点或者 null。
作者:jyd
链接:https://leetcode-cn.com/problems/fu-za-lian-biao-de-fu-zhi-lcof/solution/jian-zhi-offer-35-fu-za-lian-biao-de-fu-zhi-ha-xi-/
来源:力扣(LeetCode)
思路:对于普通的链表复制,即没有random节点,可以通过每一轮创建新节点,并维护当前节点cur和前驱节点pre,来进行复制。
class Solution {
public Node copyRandomList(Node head) {
//普通单链表
Node cur = head;
Node dum = new Node(0);
Node pre = dum;
//cur!=null,说明不为空需要复制
while(cur!=null){
Node node = new Node(cur.val);
pre.next = node;
cur = cur.next;
pre = pre.next;
}
return dum.next;
}
}
对于本题,有random节点,因此不能再像普通节点一样了。
第一种方法,构建HashMap。让新老节点进行一一对应,思路简单,但空间复杂度为O(n)
class Solution {
public Node copyRandomList(Node head) {
//用HashMap
if(head==null) return null;
//初始化
Node cur = head;
Map<Node, Node> map = new HashMap<Node,Node>();
//将新老链表对应起来
while(cur!=null){
map.put(cur, new Node(cur.val));
cur = cur.next;
}
//建立联系
cur = head;
while(cur!=null){
Node temp = map.get(cur);
temp.next = map.get(cur.next);
temp.random = map.get(cur.random);
cur = cur.next;
}
return map.get(head);
}
}
第二种思路,首先迭代创建新节点,对老链表进行拼接,老——新——老——新…,之后为新节点添加random节点,最后进行拆分,将老链表和新链表拆开,返回新链表
//拼接与拆分
if(head==null) return null;
//拼接
Node oldNode = head;
Node newNode = null;
while(oldNode!=null){
newNode = new Node(oldNode.val);
newNode.next = oldNode.next;
oldNode.next = newNode;
oldNode = newNode.next;
}
//添加random
oldNode = head;
while(oldNode!=null){
if(oldNode.random!=null){
oldNode.next.random = oldNode.random.next;
}
oldNode = oldNode.next.next;
}
//拆分
Node newHead = head.next;
oldNode = head;
newNode = head.next;
while(newNode.next!=null){
oldNode.next = oldNode.next.next;
newNode.next = newNode.next.next;
oldNode = oldNode.next;
newNode = newNode.next;
}
oldNode.next = null;
return newHead;