Reverse a Linked List
EasyLinked lists
You are given the head of a singly linked list. Reverse the list, so its last node comes first, and return the new head.
Lists in the examples are written as their values from head to tail: [1,2,3] is 1 → 2 → 3, and [] is an empty list, with no head at all.
Try it without making any new nodes: only change where each node points.
Constraints
- 0 ≤ number of nodes ≤ 5,000
- -5,000 ≤ node value ≤ 5,000
Example 1
Input
head = [1,2,3,4,5]
Output
[5,4,3,2,1]
Why:
1 → 2 → 3 → 4 → 5 becomes 5 → 4 → 3 → 2 → 1.
Example 2
Input
head = [1,2]
Output
[2,1]
Why:
The two nodes swap places: 2 now points to 1.
Example 3
Input
head = []
Output
[]
Why:
An empty list stays empty, so there is no head to return.
Hints
Was this a good challenge?
- Solved by
- 0
- Submissions
- 0
- Accepted
- –