🌑

Stephen's Blog

Doubly Linked List in Python

 

Stephen Cheng

Intro

There are three basic forms of linked lists:

  1. Singly linked lists
  2. Doubly linked lists
  3. Circular linked lists

A doubly linked list has nodes with addresses to both the previous and the next node, like in the image below, and therefore takes up more memory. But doubly linked lists are good if you want to be able to move both up and down in the list.

Implementation

Below is an implementation of a basic doubly linked list in Python:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
class Node:
def __init__(self, data):
self.data = data
self.next = None
self.prev = None

node1 = Node(3)
node2 = Node(5)
node3 = Node(13)
node4 = Node(2)

node1.next = node2

node2.prev = node1
node2.next = node3

node3.prev = node2
node3.next = node4

node4.prev = node3

print("\nTraversing forward:")
currentNode = node1
while currentNode:
print(currentNode.data, end=" -> ")
currentNode = currentNode.next
print("null")

print("\nTraversing backward:")
currentNode = node4
while currentNode:
print(currentNode.data, end=" -> ")
currentNode = currentNode.prev
print("null")

, , — May 5, 2022

Search

    Made with ❤️ and ☀️ on Earth.