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 check if the linked list is empty. If self.head is None, then the condition on line 2 will evaluate to true and we will initialize self.head to a new Node based on the input parameter data. As this is the append method for a circular linked list, we make the next of the head point to itself on line 4.
Now let’s look at the case where the linked list is not empty. In this case, we iterate the linked list to get to the last element whose next is the head node and insert the new element after that last node. On line 6, we initialize new_node by calling the constructor of the Node class and passing data to it. Next, we have to find an appropriate position in the linked list to insert new_node. For this, we set cur to self.head on line 7 and set up a while loop on line 8 which executes until the next node of the cur does not equal self.head. cur is updated to cur.next in the body of the while loop on line 9 to help us traverse the linked list. After the while loop terminates, cur will be the node that points to the head node and we will insert new_node after cur. Hence, we set cur.next equal to new_node on line 10. As we have to complete our circular chain, we set new_node.next to point to self.head on line 11. This completes our implementation for the append method.
The append method will insert an element at the end of the linked list. Below is an illustration which depicts the append functionality:
We have handled two cases of appending elements in the code above:
The doubly linked list is empty.
The doubly linked list is not empty.
If the doubly linked list is empty, i.e., self.head is None, then the execution jumps to line 3 and we initialize new_node based on data inputted to the method. As the new_node will be the only node in the linked list, we will make it the head node on line 4.
Now let’s move on to the second case. On line 6, we initialize new_node by calling the constructor of the Node class and passing data to it. Next, we need an appropriate position to locate the newly created node. Therefore, we initialize cur on line 7 to the head node to traverse the doubly linked list and reach the last node in it. This is done by the while loop in which cur updates to cur.next and the loop runs until we reach the last node where cur.next will be equal to None (lines 8-9). Once the while loop terminates, we point the next of cur to new_node on line 10. As now we have appended new_node to the linked list, we also need to care about the previous component of new_node which should now point to cur. This step is implemented on line 11.