• [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;
        }
    }
  • 相关阅读:
    CSP模拟11
    P3870 [TJOI2009]开关
    P2357 守墓人(分块)
    那一天她离我而去 (最短路)
    礼物(概率dp)
    收集邮票(概率dp)
    齿轮
    water
    【纪中受难记】——C3D4:万里无云
    zz maven eclipse svn 上传下载
  • 原文地址:https://www.cnblogs.com/qiaomu/p/4678561.html
Copyright © 2020-2023  润新知