In a doubly linked list, each node not only contains a reference or pointer to the next node, but it contains a pointer to the previous node in the sequence, The most common use of a doubly linked list is on navigation systems where both front and back navigation is required (traversing the list forward or backward), the best example of this is a browser and how it manages the next or previous page button, and also a lot of applications implement this list to make use of the Undo and Redo button functionality that is often found in many applications.
Example
This example demonstrates how to build a doubly-link linked list using
Node class
Our Node class is the foundation on which we will build our linked list, so it is very important to define all the necessary attributes that we will use later one, in this case as an example we will only work with a parameter id, to store some kind of id (school id for example), but more parameters can be easily added, it is also important to note that we will begin to work with links or pointers at this time, and in our constructor we will assign both the next and previous pointers to None (null) because we are not building the list just yet.
class Node: |
DoublyLinkedList class
Our doubly linked list class is not more than a collection of methods utilized to alter in many different ways our doubly linked list, here we can include methods such as: add(), delete(), find(), traverse(), print_list(direction), etc. in this example we will explore two methods: add() and print_list(direction), but more can be easily implemented, it is important to note that more often than note recursion is a good way of building this methods, although iteration tends to be faster, as this is a beginner example we will use iteration for the methods listed above.
class DoublyLinkedList: |
DoublyLinkedList instance
Finally we create a new instance of out DoublyLinkedList, add a couple of values and print our list to check if its working correctly.
list2 = DoublyLinkedList() #create a new DoubleLinkedList |
Output
Our output should look something like this.
1->2->3 |
Check this project on GitHub.