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.

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.分解至两个独立列表

/**
 * 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;
    }
}
原文地址:https://www.cnblogs.com/RazerLu/p/3554241.html