codejump
EasyPythonJavaScriptTypeScript

Linked List — Reverse a List

Data StructuresLinked ListTwo Pointers

solve(values) builds a singly linked list from values, **reverses it by
re-pointing the next links**, and returns the values of the reversed list as an array.
Do not copy the values into an array and reverse that — the point is to rewire the nodes
in O(n) time and O(1) extra space.

Walk the list with three references: prev (already reversed), cur (being
processed) and next (saved before you overwrite cur.next).

Examples

solve([1,2,3,4,5])  → [5,4,3,2,1]
solve([1,2])        → [2,1]
solve([])           → []

Sample tests

Test #1Five nodes
Input: [[1,2,3,4,5]]
Output: [5,4,3,2,1]
Test #2Two nodes
Input: [[1,2]]
Output: [2,1]
Test #3Empty list
Input: [[]]
Output: []