Introduction and Insertion
Explore the concept of circular linked lists and understand their structure where the tail node points to the head. Learn to implement key methods such as append, prepend, and print in Python. This lesson helps you distinguish circular linked lists from singly linked lists and prepare for solving related coding problems.
We'll cover the following...
Introduction
First of all, let’s talk about what a circular linked list is. It is very similar to a singly linked list except for the fact that the next of the tail node is the head node instead of null.
Below is an illustration to help you visualize a circular linked list:
You can see from the illustration above that the circular linked list contains the same kind of nodes as a singly linked list. As the name circular suggests, the tail node points to the head of the linked list instead of pointing to null which makes the linked list circular. Now let’s implement it in Python:
The Node class is the same as before. Also, the constructor of CircularLinkedList class is identical to the constructor of the LinkedList class. However, the methods prepend, append, and print_list will be different this time.
append
Appending to a circular linked list implies inserting the new node after the node that was previously pointing to the head of the linked list.
Let’s have a look at the code below for the append method:
One case is to append to an empty linked list. In this case, we make the new node the head of the linked list, and its next node is itself. So, we’ll ...