欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

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

程序员文章站 2022-05-06 11:33:13
...

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 复杂链表的复制
思路参考了题解
LeetCode 面试题35 复杂链表的复制

/*
// 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