Learn Before
Concept

Doubly Linked List

A doubly linked list contains a chain of nodes similar to a regular linked list except each node contains both a pointer to the next node in the chain and a pointer to the previous node in the chain.

Example implementation of a Node class:

class Node: def __init__(self, value, next = None): self.value = value self.next = next # pointer to next node self.prev = next # new pointer to the previous node

The following example is a Doubly Linked List class that creates a single head node:

class DoublyLList: def __init__(self): self.head = None

The following snippet creates a doubly linked list with 3 elements:

my_doubly_llist = DoublyLList() # creates a Doubly LinkedList object my_doubly_llist.head = Node("Hello") # sets the head's value to "Hello" element2 = Node("Good") # creates a Node with value "Good" element3 = Node("Morning") # creates a Node with value "Morning" my_doubly_llist.head.next = element2 # sets the head's next element to element2 element2.next = element3 # sets element2's next element to element3 element2.prev = my_doubly_llist.head # sets element2's prev element to head element3.prev = element2 # sets element3's prev element to element2

0

1

Updated 2021-04-13

Tags

Python Programming Language

Data Science

Related