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;
        }
    }
  • 相关阅读:
    实验吧之snake
    实验吧之Canon
    实验吧之紧急报文
    实验吧之deeeeeeaaaaaadbeeeeeeeeeef-200
    Centos Linux 使用Yum安装Go和配置环境
    harbor仓库搭建
    教你怎么半天搞定Docker
    教你分分钟搞定Docker私有仓库Registry
    kubernetes学习:CKA考试题
    Python基础知识
  • 原文地址:https://www.cnblogs.com/qiaomu/p/4678561.html
Copyright © 2011-2022 走看看