Reverse a linked list in python

 Reverse a linked list in python

To reverse a linked list in Python, you can use an iterative approach with a loop. Here is an example of how you might do this:

# Define a Node class

class Node:

  def __init__(self, value, next=None):

    self.value = value = next

# Define a LinkedList class

class LinkedList:

  def __init__(self, head=None):

    self.head = head

  def reverse(self):

    # Set the current and previous nodes

    current = self.head

    previous = None

    # Iterate through the list and reverse the links

    while current:

      next = = previous

      previous = current

      current = next

    # Set the head to the last node

    self.head = previous

# Test the LinkedList class

node1 = Node(1)

node2 = Node(2)

node3 = Node(3)

node4 = Node(4) = node2 = node3 = node4

linked_list = LinkedList(node1)


node = linked_list.head

while node:


  node =

# Output: 4 3 2 1

This approach works by iterating through the linked list and reversing the links between the nodes one at a time. The previous node starts as None and is updated to the current node after the links are reversed. The current node is updated to the next node in the list, and the process repeats until the end of the list is reached.

Post a Comment