Practice · Linked list · 2 of 6

Reverse a Linked List

You are given head, the first node of a singly linked list (or nothing, for an empty list).

Reverse the list, so its last node comes first and every next pointer points the other way, and return the new first node. Rewire the nodes you were given rather than making new ones.

Example 1

Input
head = [4, 8, 15]
Output
[15, 8, 4]

Example 2

Input
head = [7]
Output
[7]
A single node is its own reverse.

Constraints

  • The list holds 0 to 5000 nodes.
  • Every value is between −5000 and 5000.