1. 程式人生 > >138. 復制帶隨機指針的鏈表

138. 復制帶隨機指針的鏈表

sse 額外 for tno 復制 ren head list 描述

題目描述

給定一個鏈表,每個節點包含一個額外增加的隨機指針,該指針可以指向鏈表中的任何節點或空節點。

要求返回這個鏈表的深拷貝

示例:

技術分享圖片

輸入:
{"$id":"1","next":{"$id":"2","next":null,"random":{"$ref":"2"},"val":2},"random":{"$ref":"2"},"val":1}

解釋:
節點 1 的值是 1,它的下一個指針和隨機指針都指向節點 2 。
節點 2 的值是 2,它的下一個指針指向 null,隨機指針指向它自己。

提示:

  1. 你必須返回給定頭的拷貝作為對克隆列表的引用。

分析

之前刷過劍指offer,有一題一樣的,哈哈,然後用那題的思路,然後就通過了。

  1. 在舊鏈表中創建新鏈表,此時不處理新鏈表的兄弟節點
  2. 根據舊鏈表的兄弟節點,初始化新鏈表的兄弟節點
  3. 從舊鏈表中拆分得來新鏈表

貼出代碼

/*
// Definition for a Node.
class Node {
    public int val;
    public Node next;
    public Node random;

    public Node() {}

    public Node(int _val,Node _next,Node _random) {
        val = _val;
        next = _next;
        random = _random;
    }
};
*/
class Solution {
    public Node copyRandomList(Node head) {
        if(head == null){
            return null;
        }
        
        Node currentNode = head;
        
        while(currentNode != null){
            Node cloneNode = new Node(currentNode.val);
            Node nextNode = currentNode.next;
            currentNode.next = cloneNode;
            cloneNode.next = nextNode;
            currentNode = nextNode;
        }
        
        currentNode = head;
        while(currentNode != null){
            currentNode.next.random = currentNode.random == null ? null : currentNode.random.next;
            currentNode = currentNode.next.next;
        }
        currentNode = head;
        Node pCloneNode = head.next;
        while(currentNode != null){
            Node cloneNode = currentNode.next;
            currentNode.next = cloneNode.next;
            cloneNode.next = cloneNode.next == null ? null : cloneNode.next.next;
            currentNode = currentNode.next;
        }
        return pCloneNode;
    }
}

138. 復制帶隨機指針的鏈表