随机链表的复制

题目

思路

  1. 把复制节点插入到原链表中
  2. 每个旧节点紧跟着它的复制节点
  3. 复制 random 指针
  4. 拆分链表

Java

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40

class Solution {
    public Node copyRandomList(Node head) {
        if (head == null) {
            return null;
        }

        Node cur = head;
        while (cur != null) {
            Node copy = new Node(cur.val);
            copy.next = cur.next;
            cur.next = copy;
            cur = copy.next;
        }

        cur = head;
        while (cur != null) {
            Node copy = cur.next;
            copy.random = (cur.random == null) ? null : cur.random.next;
            cur = copy.next;
        }

        Node dummy = new Node(0);
        Node copyCur = dummy;

        cur = head;
        while (cur != null) {
            Node copy = cur.next;
            Node nextOld = copy.next;

            copyCur.next = copy;
            copyCur = copy;

            cur.next = nextOld;
            cur = nextOld;
        }

        return dummy.next;
    }
}