Workspace Reverse Linked List
0d
Back to questionsDSA Visualizers: 388 Coding Questions

Reverse Linked List visualizer

Construct nodes in input order, reverse their next links and return values encountered from the new head.

EXECUTION LAB

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 out

Visualizer

Step 1 of 13
4active · cur729

Inspect the current state

Save the original successor of node 0.

Variable watch

prev -1cur 0links [1,2,3,-1]

Step explanation

Save the original successor of node 0.

comparisons 8reads 0writes 5swaps 0recursiveCalls 0
Educational simulation · O(n) time · O(n) node model and returned array, O(1) reversal workspace space

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 1Turn one-way direction signs around while retaining a note of the original next stop.
Hint 2Save the next link before pointing the current node back to the previous one.
Hint 3Step 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?

Continue learning

Practice related DSA questions in the same topic.