Python Program to Reverse a Linked List without Recursion

In this Python program, we will reverse a linked list without using recursion. We’ll implement a non-recursive approach to reverse the order of elements in a singly linked list.

Problem Statement

Given a singly linked list, you need to reverse the order of its elements without using recursion.

Python Program to Reverse a Linked List without Recursion

class Node:
    def __init__(self, data):
        self.data = data
        self.next = None

class LinkedList:
    def __init__(self):
        self.head = None

    def append(self, data):
        new_node = Node(data)
        if not self.head:
            self.head = new_node
            return
        current = self.head
        while current.next:
            current = current.next
        current.next = new_node

    def reverse(self):
        prev = None
        current = self.head
        while current:
            next_node = current.next
            current.next = prev
            prev = current
            current = next_node
        self.head = prev

    def display(self):
        current = self.head
        while current:
            print(current.data, end=" -> ")
            current = current.next
        print("None")

# Example usage
if __name__ == "__main__":
    linked_list = LinkedList()
    linked_list.append(1)
    linked_list.append(2)
    linked_list.append(3)
    linked_list.append(4)

    print("Original Linked List:")
    linked_list.display()

    linked_list.reverse()

    print("\nReversed Linked List:")
    linked_list.display()

How It Works

  1. The Node class defines the individual elements of the linked list with a data attribute and a reference to the next node.
  2. The LinkedList class contains methods for appending elements, reversing the list, and displaying the list.
  3. The append method adds elements to the end of the linked list.
  4. The reverse method iterates through the list, updating the next references to reverse the connections between nodes.
  5. The display method prints the elements of the linked list.

Input/Output

Python Program to Reverse a Linked List without Recursion

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

In this Python program, we will create a singly linked list and remove duplicate elements from it. A linked list...
This Python program solves the Celebrity Problem by finding a person who is known by everyone but does not know...
This Python program uses a recursive approach to solve the n-Queens problem. It explores all possible combinations of queen placements...