栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

java实现复制带随机指针的链表(力扣138题)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

java实现复制带随机指针的链表(力扣138题)

我们要复制以上链表的。重点要保证映射关系的一致

public class Node {
    int val;
    Node next;
    Node random;

    public Node(int val) {
        this.val = val;
        this.next = null;
        this.random = null;
    }
}
public class Solution{
    public Node copyRandomList(Node head) {
        Node cur = head;
        Node newNode = null;

        //将新结点插入到对应老结点的后面
        while (cur!=null){
            newNode = new Node(cur.val);
            newNode.next = cur.next;
            cur.next = newNode;
            cur = cur.next.next;
        }

        cur = head;
        //复制random的映射关系
        while (cur!=null){
            //由于之前将新结点插入到了对应老结点后
            //通过找到老结点的random即可找到新结点random指向的结点即为老结点的random的next
            if (cur.random == null){
                cur.next.random = null;
            }else{
                cur.next.random = cur.random.next;
            }
            cur = cur.next.next;
        }

        //拆开老结点和新结点
        cur = head;
        Node newHead = head.next;
        while (cur!=null){
            newNode = cur.next;
            // 改变 cur.next 和 newNode.next
            cur.next = cur.next.next;   // newNode.next
            if (newNode.next != null) {
                newNode.next = newNode.next.next;
            }

            // 让 cur 还指向下一个老结点
            cur = cur.next;
        }
        return newHead;
    }

    public static void main(String[] args) {
        Node head = new Node(7);
        Node n1 = new Node(13);
        Node n2 = new Node(11);
        Node n3 = new Node(10);
        Node n4 = new Node(1);

        head.next = n1;
        head.random = null;
        n1.next = n2;
        n1.random = head;
        n2.next = n3;
        n2.random = n4;
        n3.next = n4;
        n3.random = n2;
        n4.next = null;
        n4.random = head;

        Node node = new Solution().copyRandomList(head);
    }

}

 

这样,我们就完成了深拷贝。 

 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/644999.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号