Reverse the Playlist

Easypointer reversalAlso known as Reverse Linked List

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

A listener taps "Play in reverse". The app must flip the chain in place, so the last song becomes the first and 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] for readability; 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

The chain was 3 → 8 → 1 → 9. After flipping every arrow it is 9 → 1 → 8 → 3, and 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

Walk the list, copy every value into an array, then build a brand-new list from the array backwards.

That is O(n) time, so speed is fine. The cost is O(n) extra memory for the array and the new nodes, and you never practise the real skill: rewiring pointers without losing your place. The in-place version uses 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