力扣——随机链表的复制
题目链接:
链接
题目描述:
思路:
思路一
利用map,先把val复制到新的node,再把关系复制到node,
key是旧的node,value是新的node
思路二
不复制在map里,而是直接复制在链表里,相当于插入一个新的node,插入后就会知道原本节点的next,但是不知道random,所以还需要再遍历一次找到random,最后拆分两个链表
实现代码:
class Solution {
public Node copyRandomList(Node head) {
Node cur = head;
Map<Node,Node> map= new HashMap<>();
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);
}
}
class Solution {
public Node copyRandomList(Node head) {
if(head==null){
return head;
}
//复制插入
Node cur = head;
while(cur != null){
Node tmp = cur.next;
cur.next = new Node(cur.val);
cur.next.next = tmp;
cur = tmp;
}
//找random
cur = head;
while(cur != null){
if(cur.random != null){
cur.next.random = cur.random.next;
}
cur = cur.next.next;
}
//拆分
Node ans = head.next, pre = head;
cur = head.next;
while(cur.next != null){
pre.next = pre.next.next;
cur.next = cur.next.next;
pre = pre.next;
cur = cur.next;
}
pre.next = null;
return ans;
}
}