A Doubly Linked List is an advanced version of Singly Linked List which has an additional pointer prev
to store the location of the previous node.
We suggest you to go over the implementation of Singly Linked List before starting with Doubly Linked List. It will become easier for you to understand Doubly Linked List if you already know how a Singly Linked list works.
A Doubly Linked list is also made up of nodes, but as compared to the node used in Singly linked list, node in case of doubly linked list have 3 parts:
Below we have a simple pictorial representation of Nodes connected to form a Doubly Linked List.
As you can see, every node has some data stored in it, and it also stores the location of the next node and the previous node. It is not necessary that all the nodes get saved in contiguos memory locations. Also, the first node's prev
pointer and the last node's next
pointer points to NULL
because there is no node before the first node and after the last node.
Head is a pointer which always points to the first node of the list, if Head points to nothing, it means the linked list is empty.
Before we move on with the implemenation let's understand the advantages of a Doubly Linked List over a Singly Linked List.
The major disadvantage is maintaining an extra prev
pointer, which not only demands extra memory space, but also adds extra steps to carry out basic operations on the Doubly Linked list as we have to update two pointers every time we insert a new node or delete a node.
To implement a Doubly Linked List, we will first define a class for Node
which will have three attributes, namely data
, prev
and next
, where next
is the pointer to store the location of the next node and prev
is the pointer to store the location of the previous node.
Then we will have the class DoublyLinkedList
, which will have the head pointer, initialized to None
. We can also have another attribute size
to store the size of the doubly linked list.
Try changing the code as you like. Click the button, to Run the code again.
/code/python/ds/doubly-linked-list-introduction-insertion.php