Linked lists · Problem 1 of 3

Reverse a playlist stored as a linked list

Pattern: Reverse a Linked List in Place

easyNot solved yet

The problem

A music app stores a playlist as a singly linked list of song IDs, where head is the first song. Write a function that reverses the playlist in place and returns the new head. The list may be empty (head is None / null).

A ListNode class with val and next is provided. In the examples and tests, lists are written as arrays: [1, 2, 3] means 1 → 2 → 3.

text
1reverse_playlist([1, 2, 3, 4])  ->  [4, 3, 2, 1]
2reverse_playlist([7])           ->  [7]
3reverse_playlist([])            ->  []
Example 11 / 2
head
1
2
3
4
null

Before: 1 → 2 → 3 → 4.

Write reverse_playlist(head) in Python or reversePlaylist(head) in JavaScript. Examples are written in Python: in JavaScript, None is null and True / False are true / false.

Runs privately in your browser. Nothing is sent to a server.Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor

Write your function, then run it against 16 tests.

Breakdown

Stuck? Reveal one step at a time, and try again after each one.

  1. Step 2
  2. Step 3
  3. Step 4

Solution

?

Give it a real try first: you learn far more from a wrong attempt than from reading the answer.