头图

LeetCode-138 - Copy linked list with random pointer

雄狮虎豹
中文

Copy linked list with random pointer

Problem description: Give you a linked list of length n, each node contains an additional random pointer random, which can point to any node in the linked list or an empty node.

Constructs a deep copy of this linked list. A deep copy should consist of exactly n new nodes, where 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 copied linked list, so that these pointers in the original linked list and the copied linked list can represent the same linked list state. None of the pointers in the copied linked list should point to the nodes 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 replication linked list also have x.random --> y .

Returns the head node of the replicated linked list.

A linked list in input/output is represented by a linked list consisting of n nodes. Each node is represented by a [val, random_index]:

  • val: An integer representing Node.val.
  • random_index: The index of the node pointed to by the random pointer (ranging 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 an incoming parameter.

For example descriptions, please refer to the official website of LeetCode.

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

Solution 1: Linked List Traversal
  • First, if the linked list is empty, return directly.
  • Otherwise, traverse the linked list in order, and use a HashMap to store the old node and copy node mapping. The traversal process is as follows:

    • If the current node has been copied, it is taken from mappings; otherwise, one is copied;
    • It is judged that if there is a random pointer in the current node, and the random of the current node has been copied, it will be taken from mappings; otherwise, one will be copied.
  • 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为旧节点,value为新节点
        Map<RandomNode, RandomNode> mappings = new HashMap<>();
        RandomNode newHead = new RandomNode(-1);
        RandomNode cur = newHead;
        // 遍历原链表
        while (head != null) {
            // 如果当前节点已经copy过,则从mappings中取;否则copy一个
            if (mappings.containsKey(head)) {
                cur.next = mappings.get(head);
            } else {
                cur.next = new RandomNode(head.val);
                mappings.put(head, cur.next);
            }

            // 如果当前节点的random已经copy过,则从mappings中取;否则copy一个
            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之前的链表");
        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之后的链表");
        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 major is not working on your own, don't refuse other directions, because many times, it is the unfamiliar road that brings you light.
阅读 593

LeetCodet题解
技术学习

玉树临风,仙姿佚貌!

1.7k 声望
7.1k 粉丝
0 条评论

玉树临风,仙姿佚貌!

1.7k 声望
7.1k 粉丝
文章目录
宣传栏