思路
根据左神视频的思路来复现的。
笔试代码就是用一个map来存储老链表和复制的链表,让其一一对应。
代码
笔试代码:
/*
// Definition for a Node.
class Node {
int val;
Node next;
Node random;
public Node(int val) {
this.val = val;
this.next = null;
this.random = null;
}
}
*/
class Solution {
public Node copyRandomList(Node head) {
Map<Node,Node> map = new HashMap<>();
Node temp = head;
while(temp != null){
map.put(temp,new Node(temp.val));
temp =temp.next;
}
Node temp1 = head;
Node temp2 = head;
while(temp1 != null){
temp2 = map.get(temp1);
temp2.next = map.get(temp1.next);
temp2.random = map.get(temp1.random);
temp1 = temp1.next;
//下面的更简洁
// map.get(temp1).next = map.get(temp1.next);
// map.get(temp1).random = map.get(temp1.random);
// temp1 = temp1.next;
}
return map.get(head);
}
}
面试代码:
这个是考虑了空间复杂度的代码
/*
// Definition for a Node.
class Node {
int val;
Node next;
Node random;
public Node(int val) {
this.val = val;
this.next = null;
this.random = null;
}
}
*/
class Solution {
public Node copyRandomList(Node head) {
if(head == null){
return null;
}
Node cur = head;
Node next = null;
Node temp = null;
//将老链表和新链表串起来
while(cur != null){
next = cur.next;
temp = new Node(cur.val);
cur.next = temp;
temp.next =next;
cur = next;
}
//设置random
cur = head;
Node random = null;
while(cur != null){
random = cur.random;
cur.next.random = random != null ? random.next:null;
cur = cur.next.next;
}
//新老链表分离
Node res = head.next;
cur = head;
temp = null;
while(cur != null){
next = cur.next.next;
temp = cur.next;
cur.next = next;
temp.next = next!=null?next.next:null;
cur = next;
}
return res;
}
}