Practice
JavaScriptData StructuresReactConcepts
Sign in
← Back to problems

Reverse a Linked List

Linked Listsmedium

Nodes are `{ val, next }` objects. Implement `reverseList(head)` that reverses a linked list in-place and returns the new head. Example: `1→2→3→null` becomes `3→2→1→null`.

Sample tests

Input: reverseList({"val":1,"next":{"val":2,"next":{"val":3,"next":null}}})
Output: {"val":3,"next":{"val":2,"next":{"val":1,"next":null}}}
Input: reverseList({"val":1,"next":null})
Output: {"val":1,"next":null}

+ 1 hidden test run on Submit.

Hints

Common pitfalls
  • Reassigning next before saving the following node loses the rest of the list.

Learning resources

  • MDN: while statement
Approach & explanation (try first)

Walk the list re-pointing each node to its predecessor, saving the next node first. O(n) time, O(1) extra space.

Loading...
⌘/Ctrl + Enter

Run your code to see results.