Anusha Murali

Logo

Please see github.com/anusha-murali for all of my repositories.

View GitHub Profile

Reversed Linked List

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

linkedList1

When the above linked list is revered, we obtain the following:

linkedList2

Example 2

linkedList3

When the above linked list is revered, we obtain the following:

linkedList4

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)$.

Back to Queues Problems


anusha-murali.github.io