How to Implement Doubly Linked List Operations in Python

In this tutorial, we will learn how to program “How to Implement Doubly Linked List Operations in Python.” The objective is to implement operations for a doubly linked list. This tutorial will guide you step by step through the process of creating and managing a doubly linked list. By the end of this tutorial, you will have a solid understanding of how to implement these tasks effectively in Python, helping you strengthen your problem-solving abilities and improve your coding skills.

This topic is straightforward and easy to understand. Simply follow the instructions provided, and you will complete it with ease. The program will guide you step by step through the process of implementing linked list operations. So, let’s dive into the coding process!

Getting Started:

First you will have to download & install the Python IDLE's, here's the link for the Integrated Development And Learning Environment for Python https://www.python.org/downloads/.

Creating Main Function

This is the main function of the application. The following code will display a simple GUI in terminal console that will display program. To do this, simply copy and paste these blocks of code into the IDLE text editor.
  1. class Node:
  2.     def __init__(self, data):
  3.         self.data = data
  4.         self.next = None
  5.         self.prev = None
  6.  
  7.  
  8. class DoublyLinkedList:
  9.     def __init__(self):
  10.         self.first = None
  11.         self.last = None
  12.  
  13.     def get_node(self, index):
  14.         current = self.first
  15.         for i in range(index):
  16.             if current is None:
  17.                 return None
  18.             current = current.next
  19.         return current
  20.  
  21.     def insert_after(self, ref_node, new_node):
  22.         new_node.prev = ref_node
  23.         if ref_node.next is None:
  24.             self.last = new_node
  25.         else:
  26.             new_node.next = ref_node.next
  27.             new_node.next.prev = new_node
  28.         ref_node.next = new_node
  29.  
  30.     def insert_before(self, ref_node, new_node):
  31.         new_node.next = ref_node
  32.         if ref_node.prev is None:
  33.             self.first = new_node
  34.         else:
  35.             new_node.prev = ref_node.prev
  36.             new_node.prev.next = new_node
  37.         ref_node.prev = new_node
  38.  
  39.     def insert_at_beg(self, new_node):
  40.         if self.first is None:
  41.             self.first = new_node
  42.             self.last = new_node
  43.         else:
  44.             self.insert_before(self.first, new_node)
  45.  
  46.     def insert_at_end(self, new_node):
  47.         if self.last is None:
  48.             self.last = new_node
  49.             self.first = new_node
  50.         else:
  51.             self.insert_after(self.last, new_node)
  52.  
  53.     def remove(self, node):
  54.         if node.prev is None:
  55.             self.first = node.next
  56.         else:
  57.             node.prev.next = node.next
  58.  
  59.         if node.next is None:
  60.             self.last = node.prev
  61.         else:
  62.             node.next.prev = node.prev
  63.  
  64.     def display(self):
  65.         current = self.first
  66.         while current:
  67.             print(current.data, end=' ')
  68.             current = current.next
  69.         print()
  70.  
  71.  
  72. # ---------------- MAIN PROGRAM ----------------
  73.  
  74. while True:
  75.     print("\n=============== Implement Doubly Linked List Operations ===============\n")
  76.  
  77.     a_dllist = DoublyLinkedList()
  78.  
  79.     print("Menu")
  80.     print("insert <data> after <index>")
  81.     print("insert <data> before <index>")
  82.     print("insert <data> at beg")
  83.     print("insert <data> at end")
  84.     print("remove <index>")
  85.     print("quit")
  86.  
  87.     while True:
  88.         print("The list: ", end='')
  89.         a_dllist.display()
  90.         do = input("What would you like to do? ").split()
  91.  
  92.         if len(do) == 0:
  93.             continue
  94.  
  95.         operation = do[0].strip().lower()
  96.  
  97.         if operation == "insert":
  98.             try:
  99.                 data = int(do[1])
  100.                 suboperation = do[2].strip().lower()
  101.                 position = do[3].strip().lower()
  102.                 new_node = Node(data)
  103.  
  104.                 if suboperation == "at":
  105.                     if position == "beg":
  106.                         a_dllist.insert_at_beg(new_node)
  107.                     elif position == "end":
  108.                         a_dllist.insert_at_end(new_node)
  109.                     else:
  110.                         print("Invalid position!")
  111.                 else:
  112.                     index = int(position)
  113.                     ref_node = a_dllist.get_node(index)
  114.                     if ref_node is None:
  115.                         print("No such index.")
  116.                         continue
  117.                     if suboperation == "after":
  118.                         a_dllist.insert_after(ref_node, new_node)
  119.                     elif suboperation == "before":
  120.                         a_dllist.insert_before(ref_node, new_node)
  121.                     else:
  122.                         print("Invalid operation!")
  123.             except:
  124.                 print("Invalid input format for insert.")
  125.  
  126.         elif operation == "remove":
  127.             try:
  128.                 index = int(do[1])
  129.                 node = a_dllist.get_node(index)
  130.                 if node is None:
  131.                     print("No such index.")
  132.                     continue
  133.                 a_dllist.remove(node)
  134.             except:
  135.                 print("Invalid input format for remove.")
  136.  
  137.         elif operation == "quit":
  138.             break
  139.         else:
  140.             print("Unknown operation.")
  141.  
  142.     opt = input("\nDo you want to try again? (yes/no): ").strip().lower()
  143.     if opt == "no":
  144.         print("Exiting program...")
  145.         break
  146.     elif opt != "yes":
  147.         print("Invalid choice. Exiting program...")
  148.         break

This Python program provides a full implementation of a doubly linked list with interactive operations. It uses `Node` and `DoublyLinkedList` classes to manage the list. Each node contains `data`, a `next` pointer, and a `prev` pointer. The `DoublyLinkedList` class supports insertion at the beginning or end of the list, insertion before or after a specified index, deletion of a node by index, and displaying the current list.

In the interactive main loop, users are presented with a menu where they can choose operations like `insert after `, `insert before `, `insert at beg`, `insert at end`, and `remove `. The program reads the command, parses it, and performs the corresponding operation on the doubly linked list, updating all `next` and `prev` pointers accordingly. After each operation, the list is displayed to show the current state. The program runs repeatedly, allowing multiple operations until the user chooses to quit, and it handles invalid inputs and out-of-bounds indices gracefully.

Output:

There you have it we successfully created How to Implement Doubly Linked List Operations in Python. I hope that this simple tutorial help you to what you are looking for. For more updates and tutorials just kindly visit this site. Enjoy Coding!

More Tutorials for Python Language

Python Tutorials