Reverse Linked List
Easy · Linked List
You are given the head of a singly linked list of integers. Rebuild the links so that the list is traversed in the opposite order and return the new head. You must produce the reversed list using the same nodes rather than just describing the order.
Examples
Input: head = [1,2,3,4,5]
Output: [5,4,3,2,1]
Why: The nodes are relinked so the last one becomes first and each node now points to its former predecessor.
Input: head = [1,2]
Output: [2,1]
Why: With only two nodes, swapping the direction of the single link reverses the order.
Input: head = []
Output: []
Why: An empty list has nothing to reverse, so it stays empty.
Constraints
0 <= length of list <= 5000, -5000 <= node value <= 5000
Practise it by voice
Describe the solution out loud and the interviewer writes exactly what you say, asks when you are vague, and runs the tests in your browser.
This statement is written for CodeSpeek. The problem is part of the NeetCode 150 list; Watch NeetCode's explanation of Reverse Linked List. Reference solutions from the NeetCode repository (MIT) are used to verify our tests.