zoukankan      html  css  js  c++  java
  • 复杂链表的复制leetcode

    复杂链表的复制

    请实现 copyRandomList 函数,复制一个复杂链表。在复杂链表中,每个节点除了有一个 next 指针指向下一个节点,还有一个 random 指针指向链表中的任意节点或者 null。

    示例1:

    输入:head = [[7,null],[13,0],[11,4],[10,2],[1,0]]
    输出:[[7,null],[13,0],[11,4],[10,2],[1,0]]
    

    步骤:

    1. 将新节点A',B',C'...插入到原链表A,B,C...

    1. 找到各节点random值,根据相对位置给新链表创建random值

    1. 分成两个链表

    /**
     * @param {Node} head
     * @return {Node}
     */
    var copyRandomList = function (head) {
        if (!head) return null;
        let now = head;
        while (now) {
            let cloneNode = new Node(now.val);
            /* 新结点插入到中间 */
            cloneNode.next = now.next;
            now.next = cloneNode;
            /* 遍历下一个 */
            now = cloneNode.next;
        }
        /* 赋random值 */
        now = head;
        while (now) {
            if (now.random)//根据相对位置找到对应节点
                now.next.random = now.random.next;
            now = now.next.next;
        }
        /* 拆分为两个新链表 */
        let root = head.next, tmp;
        now = head;
        while (now.next) {
            tmp = now.next;
            now.next = now.next.next;
            now = tmp;
        }
        return root;
    };
    
  • 相关阅读:
    附加作业
    个人总结
    wordcount
    vs2013安装及测试
    结对作业电梯调度问题
    阅读下面程序,请回答如下问题:
    补作业:随机生成二元四则运算
    软件工程的认识
    结对编程完结
    结对编程加团队编程
  • 原文地址:https://www.cnblogs.com/aeipyuan/p/13234526.html
Copyright © 2011-2022 走看看