import java.util.HashMap;
public class Main {
public static void main(String[] args) {
// Scanner sc = new Scanner(System.in);
Node p1 = new Node(null, 1, null);
Node p2 = new Node(null, 2, null);
Node p3 = new Node(null, 3, null);
Node p4 = new Node(null, 4, null);
p1.next = p2;
p2.next = p3;
p3.next = p4;
p1.random = p3;
p2.random = p4;
Node res1 = copy1(p1);
Node res2 = copy2(p1);
}
public static Node copy1(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);
}
public static Node copy2(Node head) {
if (head == null)
return null;
Node p = head;
// copy every node and insert to list
while (p != null) {
Node copy = new Node(p.val);
copy.next = p.next;
p.next = copy;
p = copy.next;
}
// copy random pointer for each new Node
p = head;
while (p != null) {
if (p.random != null) {
p.next.random = p.random.next;
}
p = p.next.next;
}
// break list to two
p = head;
Node newHead = head.next;
while (p != null) {
Node tmp = p.next;
p.next = tmp.next;
if (tmp.next != null) {
tmp.next = tmp.next.next;
}
p = p.next;
}
return newHead;
}
}
class Node {
Node next;
Node random;
int val;
public Node(int val) {
super();
this.val = val;
}
public Node(Node next, int val, Node random) {
this.next = next;
this.val = val;
this.random = random;
}
}
懵懵懂懂,知道个大概,先记录一下,今后有空再来深入学习,本文参考:
某大佬代码