2014年2月14日星期五

LeetCode - Send Feedback 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) {
        if(head==null) {
            return null;
        }
        RandomListNode p1 = head;
        while(p1!=null) {
            RandomListNode p2 = p1.next;
            RandomListNode dup = new RandomListNode(p1.label);
            p1.next = dup;
            dup.next = p2;
            p1 = p2;
        }
        p1 = head;
        while(p1!=null) {
            RandomListNode p2 = p1.next;
            RandomListNode r1 = p1.random;
            if(r1==null) {
                p2.random = null;
            } else {
                p2.random = r1.next;
            }
            p1 = p1.next.next;
        }
        p1 = head;
        RandomListNode dupHead = p1.next;
        while(p1!=null && p1.next!=null) {
            RandomListNode p2 = p1.next;
            p1.next = p2.next;
            p1 = p2;
        }
        return dupHead;
    }
}

没有评论:

发表评论