1. 程式人生 > >【LeetCode】#138複製帶隨機指標的連結串列(Copy List with Random Pointer)

【LeetCode】#138複製帶隨機指標的連結串列(Copy List with Random Pointer)

【LeetCode】#138複製帶隨機指標的連結串列(Copy List with Random Pointer)

題目描述

給定一個連結串列,每個節點包含一個額外增加的隨機指標,該指標可以指向連結串列中的任何節點或空節點。
要求返回這個連結串列的深度拷貝。

Description

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.

解法

public class Solution {
    public RandomListNode copyRandomList(RandomListNode head) {
        if(head==null){
            return null;
        }
        RandomListNode curNode = head;
        RandomListNode cpNode;
        while(curNode!=null){
            cpNode = new RandomListNode(curNode.label);
            cpNode.next = curNode.next;
            curNode.next = cpNode;
            curNode = cpNode.next;
        }
        curNode = head;
        while(curNode!=null){
            if(curNode.random!=null){
                curNode.next.random = curNode.random.next;
            }
            curNode = curNode.next.next;
        }
        curNode = head;
        RandomListNode retNode = head.next;
        while(curNode!=null){
            cpNode = curNode.next;
            curNode.next = cpNode.next;
            if(cpNode.next!=null){
                cpNode.next = cpNode.next.next;
            }else{
                cpNode.next = null;
            }
            curNode = curNode.next;
        }
        return retNode;
    }
}