LeetCode-138 - copy linked list with random pointer

Posted by dman779 on Wed, 19 Jan 2022 08:26:42 +0100

Copy linked list with random pointer

Title Description: give you a linked list with a length of n. each node contains an additional random pointer random, which can point to any node or empty node in the linked list.

Construct a deep copy of this linked list. The deep copy should consist of exactly n new nodes, in which the value of each new node is set to the value of its corresponding original node. The next pointer and random pointer of the new node should also point to the new node in the replication linked list, and these pointers in the original linked list and the replication linked list can represent the same linked list state. The pointer in the copy linked list should not point to the node in the original linked list.

For example, if there are two nodes X and Y in the original linked list, where x.random -- > y. Then the corresponding two nodes X and Y in the copy linked list also have x.random -- > y.

Returns the header node of the copy linked list.

A linked list composed of n nodes is used to represent the linked list in input / output. Each node is represented by a [val, random_index]:

  • Val: one represents node Integer of val.
  • random_index: the node index pointed by the random pointer (range from 0 to n-1); null if it does not point to any node.
    Your code only accepts the head node of the original linked list as the incoming parameter.

See LeetCode's official website for an example.

Source: LeetCode
Link: https://leetcode-cn.com/problems/copy-list-with-random-pointer/
The copyright belongs to Lingkou network. For commercial reprint, please contact the official authorization, and for non-commercial reprint, please indicate the source.

Solution 1: linked list traversal
  • First, if the linked list is empty, it will be returned directly.
  • Otherwise, traverse the linked list in order, and use a HashMap to save the old node and copy node mapping. The traversal process is as follows:
    • If the current node has been copied, it is retrieved from mappings; Otherwise, copy one;
    • Judge the current node. If there is a random pointer, judge that the random pointer of the current node has been copied, and get it from mappings; Otherwise copy one.
  • Finally, the linked list of copy is returned.
import com.kaesar.leetcode.RandomNode;

import java.util.HashMap;
import java.util.Map;

public class LeetCode_138 {
    public static RandomNode copyRandomList(RandomNode head) {
        if (head == null) {
            return head;
        }
        // key is the old node and value is the new node
        Map<RandomNode, RandomNode> mappings = new HashMap<>();
        RandomNode newHead = new RandomNode(-1);
        RandomNode cur = newHead;
        // Traverse the original linked list
        while (head != null) {
            // If the current node has been copied, it is retrieved from mappings; Otherwise copy a
            if (mappings.containsKey(head)) {
                cur.next = mappings.get(head);
            } else {
                cur.next = new RandomNode(head.val);
                mappings.put(head, cur.next);
            }

            // If the current node's random has been copied, it is retrieved from mappings; Otherwise copy a
            if (head.random != null) {
                if (mappings.containsKey(head.random)) {
                    cur.next.random = mappings.get(head.random);
                } else {
                    RandomNode randomNode = new RandomNode(head.random.val);
                    cur.next.random = randomNode;
                    mappings.put(head.random, cur.next.random);
                }
            }
            head = head.next;
            cur = cur.next;
        }

        return newHead.next;
    }

    public static void main(String[] args) {
        RandomNode head = new RandomNode(7);
        RandomNode one = new RandomNode(13);
        RandomNode two = new RandomNode(11);
        RandomNode three = new RandomNode(10);
        RandomNode four = new RandomNode(1);

        head.next = one;
        head.random = null;

        one.next = two;
        one.random = head;

        two.next = three;
        two.random = four;

        three.next = four;
        three.random = two;

        four.next = null;
        four.random = head;

        System.out.println("copy Previous linked list");
        RandomNode cur = head;
        while (cur != null) {
            System.out.println("val: " + cur.val + " | next: " + (cur.next == null ? "null" : cur.next.val) + " | random: " +
                    (cur.random == null ? "null" : cur.random.val));
            cur = cur.next;
        }

        RandomNode result = copyRandomList(head);
        System.out.println("copy Linked list after");
        RandomNode newCur = result;
        while (newCur != null) {
            System.out.println("val: " + newCur.val + " | next: " + (newCur.next == null ? "null" : newCur.next.val) + " | random: " +
                    (newCur.random == null ? "null" : newCur.random.val));
            newCur = newCur.next;
        }
    }
}

[daily message] young friends, when you find that your profession is blocked, don't refuse other directions, because many times, it is your strange road that brings you light.

Topics: Java Algorithm leetcode linked list