Skip to content
BytePatterns

Clone a Chain With Jump Links

MediumLinked Lists#pointer-relinking#in-place~30m

Problem

Each node of a singly linked chain has a value, a next link and a jump link, which points at any node of the same chain, including itself, or at nothing. Return the head of a deep copy: brand-new nodes with the same values, where every next and jump points at the corresponding new node. The original chain must look exactly as it did once you are done. Below, a chain is written as a list of (value, index the jump points at).

Examples

Input:  chain = [(3, None), (8, 0), (5, 3), (1, 1)]
Output: [(3, None), (8, 0), (5, 3), (1, 1)], built from new nodes only
Why:    the copy of 5 jumps to the copy of 1, not to the original 1
Input:  chain = [(4, 0)]
Output: [(4, 0)]
Why:    the copy's jump points at the copy itself
Input:  chain = []
Output: None
Why:    edge case, an empty chain copies to an empty chain

Hints

0 / 3

Stuck on the idea rather than the code? Copy a List With Random Links covers it.