Java implementation LeetCode 138 copy pointer list with Random

Linked list pointer 138. The copy with Random

Given a list, each node contains a random additional pointer that can point to any node in the linked list node or empty.

The requirement to return a deep copy of the list.

We use a linked list of n nodes to the input / output in a linked list. Each node with a [val, random_index] represents:

val: a Node.val integer representation.
random_index: random pointer node index (ranging from 0 to n-1); if you do not point to any node, was null.

Example 1:
Here Insert Picture Description

Input: head = [[7, null ], [13,0], [11,4], [10,2], [1,0]]
Output: [[7, null], [13,0], [11,4], [10, 2], [1,0]]
example 2:

Here Insert Picture Description

Input: head = [[1,1], [2,1]]
Output: [[1,1], [2,1]]
Example 3:

Here Insert Picture Description

Input: head = [[3, null ], [3,0], [3, null]]
Output: [[3, null], [3,0], [3, null]]
Example 4:

Input: head = []
Output: []
Explanation: the given list is empty (null pointer), and therefore returns null.

prompt:

-10000 <= Node.val <= 10000
Node.random node in the linked list is empty (null) or point.
The number of nodes does not exceed 1000.

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

    public Node(int val) {
        this.val = val;
        this.next = null;
        this.random = null;
    }
}
*/
class Solution {
     public Node copyRandomList(Node head) {
        if(head == null){
            return head;
        }
        // 空间复杂度O(1),将克隆结点放在原结点后面
        Node node = head;
        // 1->2->3  ==>  1->1'->2->2'->3->3'
        while(node != null){
            Node clone = new Node(node.val,node.next,null);
            Node temp = node.next;
            node.next = clone;
            node = temp;
        }
        // 处理random指针
        node = head;
        while(node != null){
            // !!
            node.next.random = node.random == null ? null : node.random.next;
            node = node.next.next;
        }
        // 还原原始链表,即分离原链表和克隆链表
        node = head;
        Node cloneHead = head.next;
        while(node.next != null){
            Node temp = node.next;
            node.next = node.next.next;
            node = temp;
        }
        return cloneHead;
    }
}
Released 1259 original articles · won praise 10000 + · views 840 000 +

Guess you like

Origin blog.csdn.net/a1439775520/article/details/104431996