How to Implement a Circular Singly Linked List in Python

In this tutorial, we will learn how to program “How to Implement a Circular Singly Linked List in Python.” The objective is to implement a circular singly linked list. This tutorial will guide you step by step through the process of creating and displaying the circular linked list. By the end of this tutorial, you will have a solid understanding of how to implement a circular singly linked list 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 implementation of a circular singly linked list. 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.  
  6.  
  7. class CircularLinkedList:
  8.     def __init__(self):
  9.         self.head = None
  10.  
  11.     def get_node(self, index):
  12.         if self.head is None:
  13.             return None
  14.         current = self.head
  15.         for _ in range(index):
  16.             current = current.next
  17.             if current == self.head:
  18.                 return None
  19.         return current
  20.  
  21.     def get_prev_node(self, ref_node):
  22.         current = self.head
  23.         while current.next != ref_node:
  24.             current = current.next
  25.         return current
  26.  
  27.     def insert_after(self, ref_node, new_node):
  28.         new_node.next = ref_node.next
  29.         ref_node.next = new_node
  30.  
  31.     def insert_before(self, ref_node, new_node):
  32.         prev = self.get_prev_node(ref_node)
  33.         self.insert_after(prev, new_node)
  34.  
  35.     def insert_at_end(self, new_node):
  36.         if self.head is None:
  37.             self.head = new_node
  38.             new_node.next = new_node
  39.         else:
  40.             self.insert_before(self.head, new_node)
  41.  
  42.     def insert_at_beg(self, new_node):
  43.         self.insert_at_end(new_node)
  44.         self.head = new_node
  45.  
  46.     def remove(self, node):
  47.         if self.head.next == self.head:
  48.             self.head = None
  49.         else:
  50.             prev = self.get_prev_node(node)
  51.             prev.next = node.next
  52.             if self.head == node:
  53.                 self.head = node.next
  54.  
  55.     def display(self):
  56.         if self.head is None:
  57.             print("Empty list")
  58.             return
  59.         current = self.head
  60.         while True:
  61.             print(current.data, end=" ")
  62.             current = current.next
  63.             if current == self.head:
  64.                 break
  65.         print()
  66.  
  67.  
  68. # ================= MAIN PROGRAM =================
  69. while True:
  70.     print("\n================= Circular Linked List Operations =================\n")
  71.  
  72.     clist = CircularLinkedList()
  73.  
  74.     print("Menu:")
  75.     print("insert <data> after <index>")
  76.     print("insert <data> before <index>")
  77.     print("insert <data> at beg")
  78.     print("insert <data> at end")
  79.     print("remove <index>")
  80.     print("quit")
  81.  
  82.     while True:
  83.         print("\nThe list:", end=" ")
  84.         clist.display()
  85.  
  86.         cmd = input("What would you like to do? ").strip().lower().split()
  87.  
  88.         if not cmd:
  89.             continue
  90.  
  91.         operation = cmd[0]
  92.  
  93.         if operation == "insert":
  94.             data = int(cmd[1])
  95.             new_node = Node(data)
  96.  
  97.             if cmd[2] == "at":
  98.                 if cmd[3] == "beg":
  99.                     clist.insert_at_beg(new_node)
  100.                 elif cmd[3] == "end":
  101.                     clist.insert_at_end(new_node)
  102.             else:
  103.                 index = int(cmd[3])
  104.                 ref_node = clist.get_node(index)
  105.                 if ref_node is None:
  106.                     print("No such index.")
  107.                     continue
  108.  
  109.                 if cmd[2] == "after":
  110.                     clist.insert_after(ref_node, new_node)
  111.                 elif cmd[2] == "before":
  112.                     clist.insert_before(ref_node, new_node)
  113.  
  114.         elif operation == "remove":
  115.             index = int(cmd[1])
  116.             node = clist.get_node(index)
  117.             if node is None:
  118.                 print("No such index.")
  119.             else:
  120.                 clist.remove(node)
  121.  
  122.         elif operation == "quit":
  123.             break
  124.  
  125.         else:
  126.             print("Invalid command.")
  127.  
  128.     opt = input("\nDo you want to try again? (yes/no): ").strip().lower()
  129.     if opt == "no":
  130.         print("Exiting program...")
  131.         break
  132.     elif opt != "yes":
  133.         print("Invalid choice. Exiting program...")
  134.         break

This program demonstrates a menu-driven implementation of a Circular Linked List in Python, allowing users to perform dynamic insertion and deletion operations. It defines a `Node` class to store data and a `CircularLinkedList` class that manages node connections in a circular manner, where the last node points back to the head. The program supports inserting new nodes at the beginning, at the end, before a given index, or after a given index, as well as removing a node at a specified index. Users interact with the list through clear text-based commands, and the current state of the list is displayed after each operation. The outer loop allows the entire program to be restarted or exited, making it interactive and suitable for understanding circular linked list behavior and pointer manipulation.

Output:

There you have it we successfully created How to Implement a Circular Singly Linked List 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