Oliver's Blog
  • 🤩Welcome!
  • Projects
    • RISC Game
    • Mini Amazon
    • HTTP Caching Proxy
    • Course Enrollment App
    • Fitness Tracker App
    • Voice Shopping Assistant
    • Graphics Town
  • Algo
    • Binary Search
      • Classical Binary Search
      • First Position of Target
      • Last Position of Target
      • Guess Number Higher or Lower
      • Search in a Big Sorted Array
      • Total Occurrence of Target
      • First Bad Version
      • Find Minimum in Rotated Sorted Array
      • Maximum Number in Mountain Sequence
      • Search a 2D Matrix
      • Search a 2D Matrix II
      • Search for a Range
      • Smallest Rectangle Enclosing Black Pixels
      • Find Peak Element
      • Search in Rotated Sorted Array
      • Wood Cut
      • Find the Duplicate Number
      • Sqrt(x) II
      • Maximum Average Subarray II
      • Copy Books
      • How Many Problem Can I Accept
    • Linked List
      • Insert Node in Sorted Linked List
      • Merge Two Sorted Lists
      • Merge K Sorted Lists
      • LRU Cache
      • Reverse Linked List II
      • Copy List with Random Pointer
      • Reverse Nodes in k-Group
      • Add Two Numbers
      • Swap Nodes in Pairs
      • Rotate List
      • Linked List Cycle
      • Linked List Cycle II
      • Intersection of Two Linked Lists
      • Remove Linked List Elements
      • Reverse Linked List
      • Delete Node in a Linked List
      • Odd Even Linked List
      • Partition List
    • Recursion Basics
      • Fibonacci
      • Double Factorial
      • Reverse Order Storage
      • Linked List Weighted Sum In Reverse Order
    • Binary Tree
      • 1. Traversal
        • Binary Tree Preorder Traversal
        • Binary Tree Inorder Traversal
        • Binary Tree Postorder Traversal
        • Construct Binary Tree from Inorder and Postorder Traversal
        • Minimum Depth of Binary Tree
        • Find Leaves of Binary Tree
        • Reconstruct Itinerary
      • 2. Classical Questions
        • Maximum Depth of Binary Tree
        • Average of Levels in Binary Tree
        • Binary Tree Leaf Sum
        • Invert Binary Tree
        • Binary Tree Path Sum
        • Binary Tree Path Sum II
        • Binary Tree Path Sum III
        • Clone Binary Tree
        • Sum Root to Leaf Numbers
        • Binary Tree Level Sum
        • Binary Tree Paths
      • 3. Binary Search Tree
        • Insert Node in a Binary Search Tree
        • Remove Node in Binary Search Tree
        • Validate Binary Search Tree
        • Trim a Binary Search Tree
        • Search Range in Binary Search Tree
        • Inorder Successor in BST
        • Binary Search Tree Iterator
        • Recover Binary Search Tree
      • 4. Divide and Conquer
        • Balanced Binary Tree
        • Minimum Subtree
        • Subtree with Maximum Average
        • Maximum Subtree
        • Lowest Common Ancestor of a Binary Tree
        • Lowest Common Ancestor II
        • Lowest Common Ancestor III
        • Binary Tree Maximum Path Sum II
        • Binary Tree Maximum Path Sum
        • Path Sum III
      • Convert Sorted Array to Binary Search Tree
      • Path Sum
      • Lowest Common Ancestor of a Binary Search Tree
      • Sum of Left Leaves
      • Minimum Absolute Difference in BST
      • Minimum Distance Between BST Nodes
      • Convert Sorted List to Binary Search Tree
      • Range Sum of BST
      • Kth Smallest Element in a BST
      • Find Largest Value in Each Tree Row
    • Sorting
      • Sort Integers
      • Merge Two Sorted Arrays
      • Reverse Pair
      • Sort List
      • Partition Array
      • Sort Colors
      • Kth Largest Element
      • Multi-keyword Sort
    • Two Pointers
      • Window Sum
      • Two Sum - Difference equals to target
      • Valid Palindrome
      • Remove Duplicates from Sorted Array
      • Recover Rotated Sorted Array
      • Two Sum II - Input array is sorted
      • Two Sum - Unique pairs
      • Two Sum - Closest to target
    • Queue & Stack
      • Implement Queue by Interface
      • Implement Stack
      • Implement Queue by Two Stacks
      • Implement Stack by Two Queues
      • Binary Tree Level Order Traversal
      • Valid Parentheses
      • Min Stack
      • Largest Rectangle in Histogram
      • Evaluate Reverse Polish Notation
      • Implement Queue by Linked List II
      • Basic Calculator II
      • Moving Average from Data Stream
      • Reveal Cards In Increasing Order
      • Longest Valid Parentheses
    • Hash Table
      • Rehashing
      • Valid Anagram
      • Two Sum
      • Contiguous Array
      • Anagrams
      • Remove Duplicate Numbers in Array
      • Friendship Service
    • Heap & Priority Queue
      • Heapify
      • Top k Largest Numbers II
      • K Closest Points
      • Kth Smallest Number in Sorted Matrix
      • Find Median from Data Stream
      • Sliding Window Median
      • Trapping Rain Water II
      • High Five
    • BFS
      • 1. BFS in Binary Tree
        • Check Full Binary Tree
        • Binary Tree Level Order Traversal II
        • Binary Tree Maximum Path Sum II
        • Convert Binary Tree to Linked Lists by Depth
      • 2. Connected Graph & Topologic Sorting
        • Search Graph Nodes
        • Graph Valid Tree
        • Connected Component in Undirected Graph
        • Topological Sorting
        • Course Schedule
        • Course Schedule II
        • Sequence Reconstruction
        • Clone Graph
        • Alien Dictionary
    • Array
      • Remove Element
      • Search Insert Position
      • Maximum Subarray
      • Plus One
      • Merge Sorted Array
      • Pascal's Triangle
      • Pascal's Triangle II
      • Best Time to Buy and Sell Stock
      • Best Time to Buy and Sell Stock II
      • Majority Element
      • Contains Duplicate
      • Contains Duplicate II
      • Summary Ranges
      • Missing Number
      • Move Zeroes
      • Third Maximum Number
      • Binary Search
      • Pairs of Songs With Total Durations Divisible by 60
      • 3Sum
      • Median of Two Sorted Arrays
      • Running Sum of 1d Array
      • Container With Most Water
    • String
      • Longest Substring Without Repeating Characters
      • Roman to Integer
      • Implement strStr()
      • Reverse Words in a String
      • First Unique Character in a String
      • Count Unique Characters of All Substrings of a Given String
    • Math
      • Pow(x, n)
      • Narcissistic Number
      • A + B Problem
    • Dynamic Programming
      • Fibonacci Number
      • N-th Tribonacci Number
      • Climbing Stairs
      • Min Cost Climbing Stairs
    • LeetCode vs. LintCode Table
  • React Notes
    • Optimizing Performance in React
  • Golang Notes
    • Basics
      • Setup
      • Hello World
      • Structure
      • Data Types
      • Variables
      • Operators
      • Constants
      • Decision Making
      • Loops
      • Special Statements
    • Official Tutorial Notes
      • More Types
        • Functions
        • Pointers
        • Structs
        • Arrays
        • Slices
        • Range
        • Maps
        • More Functions
      • Methods and Interfaces
        • Methods
        • Interfaces
        • Stringers
        • Errors
        • Images
        • Readers
      • Concurrency
        • Goroutines
        • Channels
        • Range and Close
        • Select
        • Mutual Exclusion
  • Miscellaneous
    • Traveling to China During a Global Pandemic
Powered by GitBook
On this page
  • Solution 1 (Java)
  • Notes
  • Scratches
  • Solution 2 (Java)
  • Notes
  • Scratches

Was this helpful?

  1. Algo
  2. Linked List

Copy List with Random Pointer

ID: 105; medium; 复制带随机指针的链表

PreviousReverse Linked List IINextReverse Nodes in k-Group

Last updated 3 years ago

Was this helpful?

Solution 1 (Java)

/**
 * Definition for singly-linked list with a random pointer.
 * class RandomListNode {
 *     int label;
 *     RandomListNode next, random;
 *     RandomListNode(int x) { this.label = x; }
 * };
 */
public class Solution {
    /**
     * @param head: The head of linked list with a random pointer.
     * @return: A new head of a deep copy of the list.
     */
    public RandomListNode copyRandomList(RandomListNode head) {
        if (head == null) return null;

        RandomListNode dummy = new RandomListNode(0);
        RandomListNode prev = dummy, newNode;
        HashMap<RandomListNode, RandomListNode> map = new HashMap<RandomListNode, RandomListNode>();

        while (head != null) {
            // deal with the core nodes
            if (!map.containsKey(head)) {
                newNode = new RandomListNode(head.label);
                map.put(head, newNode);
            } else {
                newNode = map.get(head);
            }
            prev.next = newNode;

            // deal with random pointers of the core nodes
            if (head.random != null) {
                if (!map.containsKey(head.random)) {
                    newNode.random = new RandomListNode(head.random.label);
                    map.put(head.random, newNode.random);
                } else {
                    newNode.random = map.get(head.random);
                }
            }
            prev = newNode;
            head = head.next;
        }

        return dummy.next;
    }
}

Notes

  • This solution uses a HashMap to keep track of the original nodes and their duplicates.

  • For each iteration, we first deal with the node itself. If it is not in the HashMap, we add it to the map where the key is itself and the value is its duplicate. If it is in the map, the next node for the deep copy is its value, i.e., the duplicate in the map. Next, we deal with the random pointers of the node. Using a similar approach, we point the random pointer of the node in the deep copy to a duplicate.

  • Do not forget to update prev and head. Here, prev is for constructing the new deep copy and head is just for traversing the original linked list.

  • Time complexity is O(n) and space complexity is also O(n).

Scratches

Solution 2 (Java)

/**
 * Definition for singly-linked list with a random pointer.
 * class RandomListNode {
 *     int label;
 *     RandomListNode next, random;
 *     RandomListNode(int x) { this.label = x; }
 * };
 */
public class Solution {
    /**
     * @param head: The head of linked list with a random pointer.
     * @return: A new head of a deep copy of the list.
     */
    public RandomListNode copyRandomList(RandomListNode head) {
        if (head == null) return null;
        copyNext(head);
        copyRandom(head);
        return splitLists(head);
    }

    private void copyNext(RandomListNode head) {
        RandomListNode newNode = null;
        while (head != null) {
            newNode = new RandomListNode(head.label);
            newNode.next = head.next;
            // newNode.random = head.random;
            head.next = newNode;
            head = head.next.next;
        }
    }

    private void copyRandom(RandomListNode head) {
        while (head != null) {
            if (head.random != null) {
                head.next.random = head.random.next;
            }
            head = head.next.next;
        }
    }

    private RandomListNode splitLists(RandomListNode head) {
        RandomListNode newHead = head.next;
        while (head != null) {
            RandomListNode duplicate = head.next;
            head.next = head.next.next;
            if (duplicate.next != null) {
                duplicate.next = duplicate.next.next;
            }
            head = head.next;
        }
        return newHead;
    }
}

Notes

  • This solution uses three pass to copy the original list. Thus, there are three steps:

    1. copyNext: This step creates new duplicated nodes and point their next pointers to their originals'.

    2. copyRandom: This step simply point the duplicates' random pointers to the corresponding duplicates of their original nodes' random pointers. The key operation here is head.next.random = head.random.next. The left is the random pointer of the duplicate and the right is the duplicate of the original random node.

    3. splitLists: We cut the connections between the original list and the new deep copy. Be careful with null checking in the loop to prevent NullPointerException.

  • The time complexity is still O(n), but the space complexity now is O(1).

Scratches

LintCode 炼码
Logo