LeetCode 面试题35 复杂链表的复制

https://leetcode-cn.com/problems/fu-za-lian-biao-de-fu-zhi-lcof/solution/fu-za-lian-biao-de-fu-zhi-jian-dan-yi-dong-de-san-/
LeetCode 面试题35 复杂链表的复制_第1张图片
思路参考了题解
LeetCode 面试题35 复杂链表的复制_第2张图片

/*
// 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;
        //将每个结点后新增一个双胞胎兄弟
        while(cur != null){
            Node cloneNode = new Node(cur.val);
            cloneNode.next = cur.next;
            cur.next = cloneNode;
            cur = cur.next.next;
        }
        //给新增结点的随机指针域赋值
        cur = head;
        while(cur != null){
            Node newNode = cur.next;
            newNode.random = cur.random==null?null:cur.random.next;
            cur = newNode.next;
        }

        //将新旧链表断开
        cur = head;
        Node cloneHead = cur.next;
        while(cur != null){
            Node newNode = cur.next;
            cur.next = newNode.next;
            newNode.next = newNode.next==null?null:newNode.next.next;
            cur = cur.next;
        }
        return cloneHead;
    }
}

你可能感兴趣的:(LeetCode)