AAlgoLoopSpaced repetition for LeetCode
EASYLinked ListLeetCode ↗

Reverse Linked List

The key idea

Walk the list once, and for each node flip its next pointer to point at the node you just came from. Carry a prev pointer (starting at null) that becomes the new head once you fall off the end.

Problem

Given the head of a singly linked list, reverse the list, and return the reversed list. Each node holds a value and a next pointer to the following node; the last node's next is null. Reversing the list means every next pointer is flipped so it points at the previous node instead, turning the original head into the new tail and the original tail into the new head.

Constraints

Examples

Input: head = [1,2,3,4,5] Output: [5,4,3,2,1]
Input: head = [1,2] Output: [2,1]
Input: head = [] Output: []

Complexity

Time: O(n) Space: O(1)

See the full solution

410310
Step-by-step visualization
Start free →

More Linked List problems