To prepend an element to the linked list implies to make it the head of the linked list. Let’s see how we can code this functionality for circular linked lists in Python:
The prepend method will insert an element at the beginning of the linked list, as shown in the illustration below:
Singly Linked List: Prepend
Prepend "D" to the linked list
1 of 2
We create a new node based on the data that is passed in, which in the above case is “D”. Now we want the next of this node to point to the current head of the linked list and replace the head of the linked list.
Let’s go ahead and write this code after which we’ll walk it through step by step.
We create a method called prepend. This also takes self and data since we need to tell it what to prepend to the linked list. We create a node based on the data passed into the method. Next, on line 29, we point the next of the new_node to the current head of the linked list, and then we set the head of the linked list equal to new_node on line 30. We have now prepended D to llist in the code above which previously only contained A, B, and C. You can play around and verify the prepend method for yourself!