larscheng / algo

0 stars 0 forks source link

【Check 43】2024-04-03 - 138. 随机链表的复制 #144

Open larscheng opened 3 months ago

larscheng commented 3 months ago

138. 随机链表的复制

larscheng commented 3 months ago

思路


```java
//拼接+拆分
    public Node copyRandomList(Node head) {
        if (head == null) {
            return null;
        }
        Node cur = head;
        while (cur != null) {
            //相邻复制
            Node temp = new Node(cur.val);
            temp.next = cur.next;
            cur.next = temp;
            cur = temp.next;
        }
        cur = head;
        while (cur != null) {
            //给复制节点设置random
            if (cur.random != null) {
                cur.next.random = cur.random.next;
            }
            cur = cur.next.next;
        }
        cur = head.next;
        Node pre = head;
        Node res = 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 res;
    }