In this video, we demonstrate how to reverse a singly linked list using both iterative and recursive approaches. We walk through step-by-step explanations of each method, highlighting their time and space complexities to help you choose the best approach for your needs.

206. Reverse Linked List | LeetCode Using Python

In this video, I demonstrate how to reverse a singly linked list using both iterative and recursive approaches. We walk through step-by-step explanations of each method, highlighting their time and space complexities to help you choose the best approach for your needs.

In this video, I tackle the problem of reversing a singly linked list, showcasing both iterative and recursive solutions. We provide clear, step-by-step explanations of each approach, demonstrating how they work and in the end highlighting their time and space complexities. Check out the Python code below to see these methods in action.

Python Code:

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution(object):
    def reverseList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """

        #iterative apprach

        current = head
        previous = None

        while current:
            next_node = current.next
            current.next = previous
            previous = current
            current = next_node

        return previous
  

        #Both are time complexities of O(n)

        '''#recursive approach
        if not head or not head.next:
            return head
        

        new_head = self.reverseList(head.next)

        head.next.next = head

        head.next = None

        return new_head'''

Similar Posts