Implementing a Doubly Linked List with Node Deletion in Python
In this comprehensive guide, we will delve into the process of creating a doubly linked list in Python and implementing a method to delete an element from a given position. This tutorial is designed to be accessible to developers of varying skill levels who are looking to enhance their understanding of data structures in Python.
Step 1: Defining the Node Class
The first step in creating a doubly linked list is to define a class for the nodes. Each node will connect to both the previous and the next node, forming a bidirectional chain. Here's how you can define the Node class:
class Node: def __init__(self, data): data None # Pointer to the previous node None # Pointer to the next node
Step 2: Defining the Doubly Linked List Class
Next, we need to define a class that represents the doubly linked list itself. This class will have methods to append nodes and delete a node at a specific position:
class DoublyLinkedList: def __init__(self): self.head None def append(self, data): new_node Node(data) if not self.head: self.head new_node return last self.head while last new_node new_ last def delete_at(self, position): if self.head is None or position
Step 3: Example Usage
Now that we have both the Node and DoublyLinkedList classes implemented, we can demonstrate how to create a list, append elements, and delete an element at a specific position.
if __name__ '__main__': dll DoublyLinkedList() (1) (2) (3) (4) print('Initial List:', end' ') # Print the initial list current dll.head while current: print(, end' - ') current del_node_at(2) # Delete node at position 2 (0-based index) print('') print('After Deletion:', end' ') # Print the list after deletion currentdll.head while current: print(, end' - ') current
Explanation
Node Class:Represents each element in the list with pointers to the previous and next nodes. DoublyLinkedList Class:
Contains methods to append nodes and delete a node at a specific position. Delete Method:
Handles edge cases like deleting the head or an invalid position.
This code provides a basic implementation of a doubly linked list in Python, complete with insertion and deletion functionality. You can further expand on this by adding more methods for traversing, searching, or reversing the list as needed!