Problem · Linked List
Deep Copy a Singly Linked List
Learn this problemProblem statement
Given the head head of a singly linked list, create a deep copy whose nodes share no identity with the original list.
For this exercise, after the copy is complete, change the value of the original node at zero-based position mutationIndex to newValue. Return an array containing two heads in this order:
- the mutated original list;
- the independent copy, which must still contain every value from before the mutation.
Function
copyAndMutateList(head: ListNode, mutationIndex: int, newValue: int) → ListNode[]Examples
Example 1
head = [4,7,9]mutationIndex = 1newValue = 70return = [[4,70,9],[4,7,9]]The value 7 in the original becomes 70. The copied list keeps 7, proving that its nodes are independent.
Example 2
head = [5]mutationIndex = 0newValue = -5return = [[-5],[5]]Mutating the only original node does not change the one-node copy.
Example 3
head = [1,1,2,1]mutationIndex = 3newValue = 8return = [[1,1,2,8],[1,1,2,1]]Repeated values do not affect node identity. Only the last original node changes.
Constraints
1 <= number of nodes <= 10^4.0 <= mutationIndex < number of nodes.-10^9 <= node.val, newValue <= 10^9.- The input list is finite and contains no cycle.