码迷,mamicode.com
首页 > 其他好文 > 详细

[leedcode 138] Copy List with Random Pointer

时间:2015-07-26 20:37:53      阅读:106      评论:0      收藏:0      [点我收藏+]

标签:

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;
    }
}

 

[leedcode 138] Copy List with Random Pointer

标签:

原文地址:http://www.cnblogs.com/qiaomu/p/4678561.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!