Skip to main content

Doubly Linked List

SpaceTime
AccessLookupInsertionDeletion
O(n)O(n)O(n)O(1)O(1)

Definition​

Doubly Linked List is a type of data structure in which each node contains a data part and 2 pointers, one pointing to the next node and another pointing to the previous node in the sequence.

Simplified

Doubly Linked List is like a game of hopscotch. Each square, or "node", holds an item and information about the next and previous squares. You start at the "head" and can move forward or backward to the "tail". You can also add or remove squares during the game.

Practice​

AspectPseudo Code
Prepend
prepend(value)
n = Node(value)
if head == ø:
head = n
tail = n
else:
n.previous = tail
tail.next = n
tail = n
Append
append(value):
n = Node(value)
if head == ø:
head = n
tail = n
else:
tail.next = n
n.previous = tail
tail = n
Search
search(value):
current_node = head
while current_node != ø and current_node.value != value:
current_node = current_node.next
return current_node
Delete Head
delete_head():
if head == ø:
return ø
deleted_head = head
if head.next != ø:
head = head.next
head.previous = ø
else:
tail = ø
head = ø
return deleted_head
Delete Node
delete_node(value):
current = head
while current != ø:
if current.value == value:
if current == head:
head = current.next
head.previous = ø
else:
current.previous.next = current.next
current.next.previous = current.previous
return current
current = current.next
Delete Tail
delete_tail():
if tail == ø:
print("The list is empty!")
return
if head == tail:
head = ø
tail = ø
return
prevNode = tail.previous
prevNode.next = ø
tail = prevNode
Reverse
reverse():
current_node = head
previous_node = ø
next_node = ø

while current_node != ø:
next_node = current_node.next
previous_node = current_node.previous
current_node.next = previous_node
current_node.previous = next_node
previous_node = current_node
current_node = next_node

tail = head
head = previous_node
Traverse
traversal():
current = head
while current != ø:
yield current.data
current = current.next
Reverse Traversal
reverse_traversal():
current = tail
while current != ø:
yield current.data
current = current.previous