Problem
Given the head
of a singly linked list, reverse the list, and return the reversed list.
Intuition
The problem involves reversing a singly linked list. The idea is to iterate through the list and reverse the direction of the pointers to create a reversed version of the original list.
Approach
Initialize two pointers, prev and current, to None and the head of the linked list, respectively.
Iterate through the linked list using a while loop until current becomes None.
Inside the loop:
Save the next node (nxt) of the current node.
Update the next pointer of the current node to point to the previous node (prev).
Update the prev pointer to the current node.
Update the current pointer to the next node (nxt).
After the loop, the prev pointer will be pointing to the new head of the reversed linked list.
Return the prev pointer.
Complexity
- Time complexity:
The time complexity is O(n), where n is the number of nodes in the linked list. The algorithm iterates through the entire list once.
- Space complexity:
The space complexity is O(1) since the solution uses only a constant amount of extra space for the pointers (prev, current, nxt).
Code
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
prev , current = None , head
while current:
nxt = current.next
current.next = prev
prev = current
current = nxt
return prev