1. 程式人生 > >【LeetCode】Copy List with Random Pointer 解題報告

【LeetCode】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; }
 * };
 */

【題意】

深拷貝一個連結串列,連結串列除了含有next指標外,還包含一個random指標,該指標指向字串中的某個節點或者為空。

【思路一】(來自網路)

假設原始連結串列如下,細線表示next指標,粗線表示random指標,沒有畫出的指標均指向NULL:

原連結串列

構建新節點時,指標做如下變化,即把新節點插入到相應的舊節點後面:

新結點插入到原結點之後

【Java程式碼】

public class Solution {
    public RandomListNode copyRandomList(RandomListNode head) {
        if (head == null) return null;
        
        //第一遍掃描:對每個結點進行復制,把複製出來的新結點插在原結點之後
        RandomListNode node = head;
        while (node != null) {
            RandomListNode newnode = new RandomListNode(node.label);
            newnode.next = node.next;
            node.next = newnode;
            node = newnode.next;
        }
        
        //第二遍掃描:根據原結點的random,給新結點的random賦值
        node = head;
        while (node != null) {
            if (node.random != null) node.next.random = node.random.next;
            node = node.next.next;
        }
        
        RandomListNode newhead = head.next;
        
        //第三遍掃描:把新結點從原連結串列中拆分出來
        node = head;
        while (node != null) {
            RandomListNode newnode = node.next;
            node.next = newnode.next;
            if (newnode.next != null) newnode.next = newnode.next.next;
            node = node.next;
        }
        
        return newhead;
    }
}

【參考】

http://www.cnblogs.com/TenosDoIt/p/3387000.html

http://blog.csdn.net/linhuanmars/article/details/22463599