Given the head of a singly linked list, reverse the list in-place and return the new head of the reversed linked list.
Table of Contents
Example:
Input:
Linked List: 1 -> 2 -> 3 -> 4 -> 5
Output:
Reversed Linked List: 5 -> 4 -> 3 -> 2 -> 1
Reverse Linked List Solution in C++:
#include <iostream>
// Definition for singly-linked list
struct ListNode {
int val;
ListNode* next;
ListNode(int x) : val(x), next(nullptr) {}
};
// Function to reverse a linked list
ListNode* reverseLinkedList(ListNode* head) {
ListNode* prev = nullptr;
ListNode* curr = head;
while (curr != nullptr) {
ListNode* nextNode = curr->next;
curr->next = prev;
prev = curr;
curr = nextNode;
}
return prev; // New head of the reversed linked list
}
int main() {
// Creating a sample linked list: 1 -> 2 -> 3 -> 4 -> 5
ListNode* head = new ListNode(1);
head->next = new ListNode(2);
head->next->next = new ListNode(3);
head->next->next->next = new ListNode(4);
head->next->next->next->next = new ListNode(5);
std::cout << "Original Linked List: ";
ListNode* current = head;
while (current != nullptr) {
std::cout << current->val << " -> ";
current = current->next;
}
std::cout << "nullptr" << std::endl;
ListNode* reversedHead = reverseLinkedList(head);
std::cout << "Reversed Linked List: ";
current = reversedHead;
while (current != nullptr) {
std::cout << current->val << " -> ";
current = current->next;
}
std::cout << "nullptr" << std::endl;
return 0;
}
Explanation:
- The
reverseLinkedList
function takes the head of the linked list as input and returns the new head of the reversed linked list. - We use three pointers,
prev
,curr
, andnextNode
, to reverse the linked list in-place. - We start with
prev
set tonullptr
andcurr
set to the head of the linked list. - In each iteration of the while loop, we do the following steps:
a. Store thenext
pointer of the current node (curr->next
) in thenextNode
pointer.
b. Point thenext
pointer of the current node to the previous node (curr->next = prev
), effectively reversing the link.
c. Moveprev
to the current node (prev = curr
) andcurr
to the next node (curr = nextNode
). - When we reach the end of the linked list (
curr == nullptr
), theprev
pointer will be pointing to the last node of the original list, which is the new head of the reversed linked list.
Time Complexity:
The time complexity of this solution is O(n), where n
is the number of nodes in the linked list. We visit each node once during the traversal and perform constant-time operations.
Space Complexity:
The space complexity of this solution is O(1) as we are using a constant amount of additional space for the prev
, curr
, and nextNode
pointers. The reversal is done in-place without using any additional data structures.