Reverse Linked List
2 approaches, code in every language
Problem description
You are given the head of a singly linked list. Your job is to flip the direction of every link so that the node that used to be last becomes the new front of the list.
After the reversal, return a reference to the head of the rearranged list. The values stored in the nodes stay the same; only the connections between nodes change.
Example 1
Input: head = [1,2,3,4,5]
Output: [5,4,3,2,1]
Each next-pointer is redirected backward, so traversal now starts at 5 and ends at 1.
Example 2
Input: head = [1,2]
Output: [2,1]
The two nodes swap roles: 2 becomes the head and 1 becomes the tail.
Constraints
The number of nodes is in the range [0, 5000].-5000 <= Node.val <= 5000
Create a free account to see the solution
You get the step-by-step animation, the intuition and clean code in every language. Free, no credit card.
After the pattern
Now solve one you haven't seen.
Rewind the Telemetry Chain is our own problem on the technique behind Reverse Linked List: a new statement, so there's no answer to remember. Write it in your browser and run it against graded tests.
1,194 problems · 15,062 graded tests · free