Back to: Python Data Structure and Algorithims
Introduction to Doubly Linked Lists
In this lesson, we’re going to begin working with Doubly Linked Lists.
Our goal is to create the constructor that initializes this data structure.
Before we dive into code, let’s start by reviewing what we already know from Singly Linked Lists.
🧱 Revisiting Singly Linked Lists
In a singly linked list, each node stores:
-
A value
-
A pointer to the next node (
next)
Visually, it looks like this:
And the node constructor looked like this:
🔁 Transitioning to a Doubly Linked List
A doubly linked list is very similar, but each node has two pointers:
-
One pointing to the next node
-
Another pointing to the previous node
This allows traversal in both directions — forward and backward.
Visually, it looks like this:
🧩 Step 1: Creating the Node for a Doubly Linked List
Just like before, we’ll create a Node class — but this time, we’ll add one extra property: previous.
Here’s the code:
✅ The only difference between this and the singly linked list node is the additional pointer:
Initially, both next and previous are None, since the node isn’t connected yet.
🧩 Step 2: Building the Doubly Linked List Class
Now that we can create nodes, let’s build our main DoublyLinkedList class.
This class will:
-
Accept a value to create the first node.
-
Set that node as both the head and the tail.
-
Initialize the length of the list to
1.
Here’s how the constructor looks:
🧠 How This Works
When you run:
It will:
-
Create a new node with value
7. -
Set both head and tail to point to this node.
-
Set the length to
1.
So visually, your structure looks like this:
🖨️ Step 3: Adding a Print Method (for Visualization)
Just like with singly linked lists, we’ll create a helper method to print out the values.
This helps us see the current state of our list.
💻 Step 4: Running the Code in VS Code
Here’s the full setup:
Output:
✅ Result
Everything works perfectly!
We successfully created:
-
A Node class with
value,next, andprevious. -
A DoublyLinkedList constructor that initializes head, tail, and length.
🧠 Key Takeaways
-
A doubly linked list allows two-way traversal.
-
Each node has
value,next, andpreviouspointers. -
The constructor initializes:
-
Head → first node
-
Tail → first node
-
Length → 1
-