Reverse a linked list.
The solution is as follows:
class Solution:
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
curr = head
prev = None
while curr:
temp = curr.next
curr.next = prev
prev = curr
curr = temp
return prev
_ Time Complexity:
O(n) - We traverse all nodes within the linked list.
_ Space Complexity:
O(1) - We maintain three pointers, curr, prev, and temp.