Reverse the Playlist

Easypointer reversalAlso known as Reverse Linked List

A music app stores each playlist as a chain of songs. Every song knows only which song comes next; there is no way to jump back.

A listener taps "Play in reverse". The app must flip the chain in place, so every song points to the one that used to come before it.

Your task

Write reversePlaylist(head). head is the first node of a singly linked list (each node has val and next). Reverse the list and return the new first node.

An empty playlist is null (None in Python). Lists are shown as arrays like [3, 8, 1, 9]; your function receives and returns real nodes.

reversePlaylist(head: ListNode) → ListNode

Examples

Example 1
Input
head = [3, 8, 1, 9]
Output
[9, 1, 8, 3]
Why

3 → 8 → 1 → 9 with every arrow flipped is 9 → 1 → 8 → 3. The new head is 9.

Example 2
Input
head = []
Output
[]
Why

An empty playlist stays empty. Return null (None in Python).

Constraints

  • 0 ≤ number of songs ≤ 5,000
  • Song ids are integers.
  • Reverse the links; do not just create a reversed copy of the values (though that also passes the tests, it misses the point).
Start with brute force

Copy every value into an array, then build a new list from the array backwards.

That takes O(n) time but also O(n) extra memory, and it avoids the real skill, which is rewiring pointers without losing your place. The in-place version needs only O(1) extra memory.

Hints

0 of 4 shown

Walkthrough and solution

Unlocks when you pass every test. Stuck for a while? Looking is fine too, as long as you then close it and write the code yourself.

Ctrl+Enter runs

Run your code to see results here. Run checks the examples. Submit checks every test, including hidden edge cases.

Write code