How to Implement a Forward and Backward Linked List in Python?

75 views

How to Implement a Forward and Backward Linked List in Python?

How to Implement a Forward and Backward Linked List in Python?

How can you implement a doubly linked list in Python?

solveurit24@gmail.com Changed status to publish February 20, 2025
0

A doubly linked list allows traversal in both directions. Here’s an implementation:

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

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

    def append(self, data):
        new_node = Node(data)
        if self.head is None:
            self.head = new_node
            new_node.prev = None
        else:
            current = self.head
            while current.next is not None:
                current = current.next
            current.next = new_node
            new_node.prev = current
            new_node.next = None

    def prepend(self, data):
        new_node = Node(data)
        new_node.next = self.head
        new_node.prev = None
        if self.head is not None:
            self.head.prev = new_node
        self.head = new_node

    def print_list_forward(self):
        current = self.head
        while current:
            print(current.data)
            current = current.next

    def print_list_backward(self):
        current = self.head
        while current.next is not None:
            current = current.next
        while current:
            print(current.data)
            current = current.prev

dll = DoublyLinkedList()
dll.append(1)
dll.append(2)
dll.prepend(0)
print("Forward traversal:")
dll.print_list_forward()  # Output: 0, 1, 2
print("Backward:")
dll.print_list_backward()  # Output: 2, 1, 0

solveurit24@gmail.com Changed status to publish February 20, 2025
0