![]() ![]() In case if the list is not empty, a message is simply displayed to the user that the list is not empty.Īdd the insert_in_emptylist() method to the DoublyLinkedList class that you created earlier. Finally, the value of self.start_node variable is set to the new node. Next, a new node is created and its value is initialized by the value passed as a parameter to the data parameter of the insert_in_emptylist() function. If the variable is None, it means that the list is actually empty. The method first checks whether the self.start_node variable is None or not. In the script above, we define a method insert_in_emptylist(). The following script inserts an element at the start of the doubly linked list: def insert_in_emptylist( self, data): if self.start_node is None: The easiest way to insert an item in a doubly linked list is to insert an item in the empty list. In this section, we will see the different ways of inserting items in a doubly linked list. Throughout this article we will keep adding functions to this class. Add the following code: class DoublyLinkedList: def _init_( self): Next, we need to create the DoublyLinkedList class, which contains different doubly linked list related functions. The nref stores the reference to the next node, while pref stores the reference to the previous node in the doubly linked list. ![]() The item variable will store the actual data for the node. You can see in the above code, we create a Node class with three member variables: item, nref, and pref. Add the following code to your file: class Node: def _init_( self, data): If you have read Part 1 and Part 2 of this series of articles, the code should be pretty straight-forward.Īs always, let's first create a class for the single node in the list. ![]() In this section, we will see how we can create a very simple doubly linked list in Python. Implementing the Doubly Linked List with Python
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |