首页 > 其他 > 详细

Copy List with Random Pointer

时间:2014-02-18 23:30:34      阅读:681      评论: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.

Ref: http://fisherlei.blogspot.com/2013/11/leetcode-copy-list-with-random-pointer.html

如图分三步:

http://lh6.ggpht.com/-xlfWkNgeNhI/Uomwl3lB47I/AAAAAAAAHsQ/V8DofvkKR68/s1600-h/image%25255B8%25255D.png

1. 插入拷贝节点

2. 复制random指针

3.分解至两个独立列表

 

bubuko.com,布布扣
/**
 * 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) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
        if(head == null){
            return head;
        }
        
        cloneNodes(head);
        setRandomPointer(head);
        return reconnectNodes(head);
    }
    
     public RandomListNode cloneNodes(RandomListNode head){
        RandomListNode p1 = head;
        while(p1 != null){
            RandomListNode c1 = new RandomListNode(p1.label);
            c1.next = p1.next;
            p1.next = c1;
            p1 = c1.next;
        }
        return head;
    }
    
    public RandomListNode setRandomPointer(RandomListNode head){
        RandomListNode p1 = head;
        while(p1 != null){
            RandomListNode r1 = p1.random;
            if(r1 != null){
                p1.next.random = r1.next;
            }
            p1 = p1.next.next;
        }
        return head;
    }
    
    public RandomListNode reconnectNodes(RandomListNode head){
        RandomListNode cloneHead = head.next;
        RandomListNode p1 = head;
        RandomListNode p2 = cloneHead;
        while(p1 != null && p2 != null){
            p1.next = p2.next;
            p1 = p1.next;
            if(p1 != null){
                p2.next = p1.next;
            }
            p2 = p2.next;
        }
        return cloneHead;
    }
}
bubuko.com,布布扣

Copy List with Random Pointer

原文:http://www.cnblogs.com/RazerLu/p/3554241.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!