Continue learning
Practice related DSA questions in the same topic.
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.
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 outSave the original successor of node 0.
Save the original successor of node 0.
Turn one-way direction signs around while retaining a note of the original next stop.
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
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]
Rewiring before saving the old link loses the rest of the list.
How would you reverse a sublist between two positions?