πDay 1. Reverse a linked list π§
The problem can be found at the following link: Problem Link
π‘ Problem Description:
You are given the head of a singly linked list. Your task is to reverse the list and return the reversed head.
π Example Walkthrough:
Input:
head: 1 -> 2 -> 3 -> 4 -> NULL
Output:
head: 4 -> 3 -> 2 -> 1 -> NULL
Explanation:
Input:
head: 2 -> 7 -> 10 -> 9 -> 8 -> NULL
Output:
head: 8 -> 9 -> 10 -> 7 -> 2 -> NULL
Explanation:
Input:
head: 10 -> NULL
Output:
head: 10 -> NULL
Explanation:
Constraints:
1 <= number of nodes, data of nodes <= $10^5$
π― My Approach:
Iterative Reversal Algorithm: The problem can be efficiently solved using an iterative approach by traversing the linked list and reversing the
next
pointers of each node.Start with two pointers:
prev
(initialized toNULL
) andcurrent
(initialized to the head of the list).In each iteration, update the
next
pointer of thecurrent
node to point to theprev
node, then moveprev
andcurrent
forward.Continue the process until the entire list is reversed.
Steps:
Initialize
prev
toNULL
andcurrent
to the head of the list.Traverse the list while
current
is notNULL
.For each node, reverse the
next
pointer to point toprev
.Move the
prev
andcurrent
pointers one step forward.Once the list is completely reversed, return
prev
as the new head.
π Time and Auxiliary Space Complexity
Expected Time Complexity: O(n), where
n
is the number of nodes in the linked list. We traverse the entire list once.Expected Auxiliary Space Complexity: O(1), as we only use a constant amount of additional space (for the
prev
andcurrent
pointers).
π Solution Code
Code (C++)
class Solution {
public:
Node* reverseList(Node* head) {
Node *prev = NULL, *curr = head, *next;
while (curr) {
next = curr->next;
curr->next = prev;
prev = curr;
curr = next;
}
return prev;
}
};
Code (Java)
class Solution {
Node reverseList(Node head) {
Node prev = null;
while (head != null) {
Node next = head.next;
head.next = prev;
prev = head;
head = next;
}
return prev;
}
}
Code (Python)
class Solution:
def reverseList(self, head):
prev = None
while head:
next = head.next
head.next = prev
prev = head
head = next
return prev
π― Contribution and Support:
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: Any Questions. Letβs make this learning journey more collaborative!
β If you find this helpful, please give this repository a star! β
πVisitor Count
Last updated