Track your progress, run tests, and get AI feedback
Run code and see test results
Submit and get AI-powered feedback
Track which problems you've solved
Reverse a Singly Linked List Iteratively
This problem challenges you to reverse the order of nodes in a singly linked list. Given the head of a linked list, your task is to return the head of the reversed list. This fundamental operation is a common interview question and tests your understanding of pointer manipulation and linked list traversal.
Implement a function reverseList that takes the head of a singly linked list as input and returns the new head of the list after its nodes have been reversed.
Input:
head: A ListNode object, representing the head of a singly linked list. It can be null if the list is empty.Output:
ListNode object, representing the head of the reversed linked list. This will be null if the input list was empty.ListNode DefinitionFor your convenience, the ListNode class is defined as follows:
class ListNode {
val: number;
next: ListNode | null;
constructor(val?: number, next?: ListNode | null) {
this.val = (val===undefined ? 0 : val);
this.next = (next===undefined ? null : next);
}
}
(The JavaScript definition is similar.)
head is null) or contains a single node, return the head itself. The reversal operation doesn't change these specific cases.ListNode objects for the reversal.Examples
Example 1
Input:
head = [1,2,3,4,5]
Output:
[5,4,3,2,1]
Note:
The original list is 1 -> 2 -> 3 -> 4 -> 5. After reversing, it becomes 5 -> 4 -> 3 -> 2 -> 1.
Example 2
Input:
head = [1,2]
Output:
[2,1]
Note:
The original list is 1 -> 2. After reversing, it becomes 2 -> 1.
Example 3
Input:
head = []
Output:
[]
Note:
An empty list remains empty after reversal.
Constraints
[0, 5000].-5000 <= Node.val <= 5000.ListNode objects should be created for the reversal process.