Reverse Linked List
Construct nodes in input order, reverse their next links and return values encountered from the new head.
Construct nodes in input order, reverse their next links and return values encountered from the new head.
Input and constraints
- Use at most 32 integers. Each numeric input is between -1000 and 1000.
Code inspector
def solve(values, target): links = [0] * (len(values)) i = 0 while (i < len(values)): links[i] = (i + 1) i = (i + 1) if (len(values) > 0): links[(len(values) - 1)] = -1 prev = -1 cur = 0 if (len(values) == 0): cur = -1 while (cur != -1): nxt = links[cur] links[cur] = prev prev = cur cur = nxt out = [0] * (len(values)) i = 0 while (prev != -1): out[i] = values[prev] prev = links[prev] i = (i + 1) return outVisualizer
Step 1 of 13Inspect the current state
Save the original successor of node 0.
Variable watch
Step explanation
Save the original successor of node 0.
Worked explanation
Turn one-way direction signs around while retaining a note of the original next stop.
Guided solution
Save the next link before pointing the current node back to the previous one.
O(n) time · O(n) node model and returned array, O(1) reversal workspace auxiliary space
Examples
Worked example · {"values":[4,7,2,9],"target":0} ⇒ [9,2,7,4]
Edge case 1 · {"values":[],"target":0} ⇒ []
Edge case 2 · {"values":[8],"target":0} ⇒ [8]
Progressive hints
Hint 1
Turn one-way direction signs around while retaining a note of the original next stop.Hint 2
Save the next link before pointing the current node back to the previous one.Hint 3
Step through the worked example and inspect the highlighted variables before each update.Common mistake
Rewiring before saving the old link loses the rest of the list.
Interview follow-up
How would you reverse a sublist between two positions?