Search⌘ K

Append and Prepend

Explore the append and prepend operations in doubly linked lists using Python. Understand how to add elements to both ends, implement these methods with detailed code, and verify your list structure with a print method.

We'll cover the following...

In this lesson, we introduce the doubly linked list data structure and code up an implementation of this data structure in Python.

After that, we look at how to append (add elements to the back of the doubly linked list) and prepend (add elements to the front of the doubly linked list).

Finally, we will write a print method to verify that the append and prepend methods work as expected.

As you can see, the doubly linked list is very similar to the singly linked list except for the difference of the previous pointer. In a doubly linked list, a node is made up of the following components:

  • Data
  • Next (Points to the next node)
  • Prev (Points to the previous node)

As illustrated, the prev of the head node points to NULL while the next of the tail node also points to NULL.

Let’s go ahead and implement the Doubly Linked List in Python:

Python 3.5
class Node:
def __init__(self, data):
self.data = data
self.next = None
self.prev = None
class DoublyLinkedList:
def __init__(self):
self.head = None
def append(self, data):
pass
def prepend(self, data):
pass
def print_list(self):
pass

We have two classes in the code above:

  1. Node
...