Ctrl K

Flip the Chain

Easy
Train cars are coupled into a singly linked list: each node knows only the next one. You are given the list's head. Recouple the cars so they run in the opposite order, and return the new head, which is the former last node. An empty list (head is None) stays empty. Try solving it two ways: with a loop and with recursion.
Example 1
head=list_node([7, -2, 0, 15]) → [15, 0, -2, 7]

The nodes come in reverse order: the last one (15) becomes the head and the first one (7) becomes the tail.

Example 2
head=list_node([42]) → [42]

A single-node list stays the same when reversed.

Example 3
head=list_node([]) → None

An empty list stays empty.

Constraints
  • 0 ≤ number of nodes ≤ 5000
  • -5000 ≤ Node.val ≤ 5000
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsZip Two Sorted Chains EasyCut Out Matching Nodes EasySymmetric Bead String EasyAdding Digit Lists MediumTrade Places in Twos Medium
loading Python…
Input
head=list_node([7, -2, 0, 15])
Expected
[15, 0, -2, 7]

Run checks the first 3 tests in your browser. Submit checks all 102 tests on the server, hidden ones included.