Please see github.com/anusha-murali for all of my repositories.
This is a nice problem from LeetCode (Problem #206).
Problem: Given the head of a singly linked list, reverse the list, and return the reversed list.
Example 1
When the above linked list is revered, we obtain the following:
Example 2
When the above linked list is revered, we obtain the following:
Example 3
An empty linked list is always reversed to an empty linked list.
Solution
# 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]:
currNode = head
prevNode = None
while currNode != None:
temp = currNode.next
currNode.next = prevNode
prevNode = currNode
currNode = temp
return prevNode
Runtime:
The time complexity is $O(n)$ and the space complexity is $O(1)$.