Python program to create and display a doubly linked list

A doubly linked list is a data structure where each node contains data and two pointers - one pointing to the next node and another to the previous node. This allows traversal in both directions.

Node Class Structure

First, we create a Node class that represents individual elements in the doubly linked list ?

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

Doubly Linked List Implementation

The main class manages the list with head and tail pointers, and provides methods to add data and display the list ?

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

class DoublyLinkedList:
    def __init__(self):
        self.head = None
        self.tail = None
    
    def add_data(self, my_data):
        new_node = Node(my_data)
        if self.head == None:
            self.head = self.tail = new_node
            self.head.prev = None
            self.tail.next = None
        else:
            self.tail.next = new_node
            new_node.prev = self.tail
            self.tail = new_node
            self.tail.next = None
    
    def print_it(self):
        curr = self.head
        if self.head == None:
            print("The list is empty")
            return
        print("The nodes in the doubly linked list are:")
        while curr != None:
            print(curr.data)
            curr = curr.next

# Create and populate the doubly linked list
my_list = DoublyLinkedList()
print("Elements are being added to the doubly linked list")
my_list.add_data(10)
my_list.add_data(24)
my_list.add_data(54)
my_list.add_data(77)
my_list.add_data(92)
my_list.print_it()
Elements are being added to the doubly linked list
The nodes in the doubly linked list are:
10
24
54
77
92

How It Works

The implementation consists of two main components:

  • Node Class: Each node stores data and maintains references to both next and previous nodes
  • DoublyLinkedList Class: Manages the list with head and tail pointers for efficient insertion
  • add_data() method: Adds new nodes at the end of the list, updating the tail pointer
  • print_it() method: Traverses from head to tail, displaying each node's data

Key Features

Feature Description
Bidirectional Traversal Can move forward and backward through nodes
Dynamic Size Grows and shrinks during runtime
Memory Efficiency Allocates memory only when needed

Conclusion

Doubly linked lists provide bidirectional traversal capabilities through prev and next pointers. The implementation uses a Node class for individual elements and a main class to manage the list structure with head and tail references.

Updated on: 2026-03-25T17:16:45+05:30

881 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements