zoukankan      html  css  js  c++  java
  • [leedcode 138] Copy List with Random Pointer

    A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.

    Return a deep copy of the list.

    /**
     * Definition for singly-linked list with a random pointer.
     * class RandomListNode {
     *     int label;
     *     RandomListNode next, random;
     *     RandomListNode(int x) { this.label = x; }
     * };
     */
    public class Solution {
        public RandomListNode copyRandomList(RandomListNode head) {
            //剑指offer26题,p147
            if(head==null) return null;
            RandomListNode cur=head;
            while(cur!=null){//第一步,复制node节点N',放在原始节点N的后面
                RandomListNode newNode=new RandomListNode(cur.label);
                newNode.next=cur.next;
                cur.next=newNode;
                cur=newNode.next;
            }
            cur=head;
            while(cur!=null){//第二步,复制random指针
                if(cur.random!=null){
                    cur.next.random=cur.random.next;
                }
                cur=cur.next.next;
            }
            cur=head;//第三步,把长链表拆分成两个链表,注意尾节点的处理方式
            RandomListNode res=head.next;
            RandomListNode pnode=res;
            while(cur!=null){
                cur.next=cur.next.next;
                cur=cur.next;
                if(pnode.next!=null)////尾节点
                pnode.next=pnode.next.next;
                pnode=pnode.next;
            }
            return res;
        }
    }
  • 相关阅读:
    Qt 解析EXcel文件
    Qt PC 安卓 tcp传输文件
    Qt listwigwt item 加入自定义元素
    Qt 独立运行时伴随CMD命令窗口
    xml模块
    shelve模块
    json模块 pickle模块
    sys 模块
    os模块
    添加变量
  • 原文地址:https://www.cnblogs.com/qiaomu/p/4678561.html
Copyright © 2011-2022 走看看