297. Reverse a Linked List

EasyLinked ListLinked ListTwo PointerIterative

Given the head of a singly linked list, reverse the list and return the reversed list's head.

The linked list is represented as a sequence of space-separated integers. Your function receives the head node and must reverse the links in-place, returning the new head.

Input: A singly linked list represented by its head node containing integer values.

Output: The head of the reversed linked list.

Examples

Example 1
Input: [1,2,3,4,5]
Output: [5,4,3,2,1]
Explanation: Original list: 1→2→3→4→5→NULL
Step 1: prev=NULL, curr=1. Set curr.next=NULL, prev=1, curr=2.
Step 2: prev=1,   curr=2. Set curr.next=1,    prev=2, curr=3.
Step 3: prev=2,   curr=3. Set curr.next=2,    prev=3, curr=4.
Step 4: prev=3,   curr=4. Set curr.next=3,    prev=4, curr=5.
Step 5: prev=4,   curr=5. Set curr.next=4,    prev=5, curr=NULL.
Return prev=5. Result: 5→4→3→2→1→NULL.
Example 2
Input: [1,2]
Output: [2,1]
Explanation: Original: 1→2→NULL.
Step 1: prev=NULL, curr=1. Set curr.next=NULL, prev=1, curr=2.
Step 2: prev=1,   curr=2. Set curr.next=1,    prev=2, curr=NULL.
Return 2. Result: 2→1→NULL.
Example 3
Input: [7]
Output: [7]
Explanation: Single node list. No reversal needed. Return the same node.

Constraints

Asked by

AdobeApplePaytmMicrosoftBloombergOracle
Solve this problem in the editor →