reverse a linked list in python

To reverse a linked list in python, we need to change the direction of pointers in the list. The head node becomes the tail node, and each node's next pointer becomes its previous pointer. Here's the algorithm to reverse a linked list.

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

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

    # method to reverse the linked list
    def reverse(self):
        prev_node = None
        current_node = self.head
        next_node = None

        # traverse the linked list and change the pointers direction
        while current_node is not None:
            next_node = current_node.next
            current_node.next = prev_node
            prev_node = current_node
            current_node = next_node

        # set the new head node as the old tail node
        self.head = prev_node
664 chars
25 lines

You can call the reverse method of the linked list object to reverse the linked list.

gistlibby LogSnag