Python Program to Implement a Doubly Linked List
Intermediate · Data structures
A doubly linked list is a linked list where every node has two links, one to the next node and one to the previous node. The extra link lets you walk the list in both directions and unlink a node without searching for the one before it. This program adds nodes, deletes them from the start and the middle, and prints the list forwards and backwards, including when it is empty.
Program
Empty list: Forward: (empty) Backward: (empty) After adding 10, 20, 30, 40: Forward: 10 <-> 20 <-> 30 <-> 40 Backward: 40 <-> 30 <-> 20 <-> 10 After deleting 10 and 30: Forward: 20 <-> 40 Backward: 40 <-> 20 Cannot delete 99 because it is not in the list
How it works
- Each
Nodehas aprevand anextlink, and the list keeps both its first node,head, and its last node,tail, which areNonewhile it is empty. append()links the new node after the tail in both directions,node.prev = self.tailandself.tail.next = node, and then makes it the new tail.delete()finds the node, then makes the node before it point forward past it and the node after it point back past it, so it drops out of both directions.- When the deleted node has no node before or after it, it was the head or the tail, so
headortailmoves instead. show()walks forward from the head withnextand backward from the tail withprev, and both walks must give the same items in opposite orders, which is a good check that every link is right.
Another way to write it
Using collections.deque
Forward: [10, 20, 30, 40] Backward: [40, 30, 20, 10] Removed from the front: 10 Removed from the back: 40 Now: [20, 30]
Python's collections.deque is built as a doubly linked list of blocks, so adding and removing at either end is fast, the main strength of a doubly linked list, and real programs use it instead of writing their own.
Try it yourself
Add a prepend(data) method that puts a new node before the head, remembering to set both links.
Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.
Related programs
All Python programs · CBSE class 12 practical file · Python exercises