To achieve a linked list data structure that allows:
- Insertion at the beginning in O(1) time, and
- Deletion of nodes from the middle in O(1) time,
we can utilize a Doubly Linked List.
A Doubly Linked List maintains pointers to both the previous and next nodes for each node in the list. This bidirectional linkage allows for efficient insertion and deletion operations when you have direct access to the node involved.
Below is a Python implementation of such a data structure, including the insert_at_beginning and delete_node functions.
Implementation
class Node:
"""
A Node in a Doubly Linked List.
"""
def __init__(self, data):
self.data = data # The value stored in the node
self.prev = None # Pointer to the previous node
self.next = None # Pointer to the next node
class DoublyLinkedList:
"""
A Doubly Linked List supporting O(1) insertion at the beginning
and O(1) deletion of a given node.
"""
def __init__(self):
self.head = None # Initialize the head of the list
def insert_at_beginning(self, data):
"""
Inserts a new node with the given data at the beginning of the list.
Time Complexity: O(1)
"""
new_node = Node(data) # Create a new node
new_node.next = self.head # New node points forward to the current head
if self.head:
self.head.prev = new_node # Current head points back to the new node
self.head = new_node # Update the head to the new node
print(f"Inserted {data} at the beginning.")
def delete_node(self, node):
"""
Deletes the specified node from the list.
Assumes that the node is part of the list.
Time Complexity: O(1)
"""
if node.prev:
node.prev.next = node.next # Bypass the node by linking previous node to next node
else:
# If node.prev is None, the node is head
self.head = node.next # Update head to the next node
if node.next:
node.next.prev = node.prev # Bypass the node by linking next node to previous node
# Optional: Clear the deleted node's pointers
node.prev = None
node.next = None
print(f"Deleted node with data: {node.data}")
def display(self):
"""
Displays the list from head to tail.
"""
current = self.head
elems = []
while current:
elems.append(current.data)
current = current.next
print("List: " + " <-> ".join(map(str, elems)))
# Example Usage
if __name__ == "__main__":
dll = DoublyLinkedList()
# Insert nodes at the beginning
dll.insert_at_beginning(10)
dll.insert_at_beginning(20)
dll.insert_at_beginning(30)
dll.display() # Output: List: 30 <-> 20 <-> 10
# Delete the middle node (20)
middle_node = dll.head.next # Assuming we have a reference to the node
dll.delete_node(middle_node)
dll.display() # Output: List: 30 <-> 10
# Delete the head node (30)
dll.delete_node(dll.head)
dll.display() # Output: List: 10
Explanation
-
Node Class:
- Each node contains
data, a prev pointer to the previous node, and a next pointer to the next node.
-
DoublyLinkedList Class:
-
Usage Example:
- Demonstrates inserting nodes at the beginning and deleting specific nodes, maintaining O(1) time complexity for both operations.
Key Points
-
Direct Access: The delete_node function assumes that you have a direct reference to the node you want to delete. This is crucial for maintaining O(1) deletion time. If you need to search for the node, that search could take O(n) time.
-
Doubly Linked Structure: The presence of both prev and next pointers is what allows for efficient deletion from the middle of the list without traversing from the head or tail.
-
Memory Management: In languages like C or C++, you'd need to manually manage memory (e.g., using free). In high-level languages like Python, clearing the pointers (node.prev = None, node.next = None) helps the garbage collector reclaim memory if there are no other references to the node.
Alternative Considerations
-
Singly Linked List: If you only used a singly linked list, deleting a node from the middle would generally require traversal from the head to find the previous node, resulting in O(n) time complexity for deletion.
-
Sentinel Nodes: To simplify edge cases (like deleting the head or tail), sometimes sentinel nodes (dummy head and tail) are used, though they aren't strictly necessary for achieving O(1) operations.
By using a Doubly Linked List and maintaining direct references to nodes when performing deletions, you can efficiently manage both insertions at the beginning and deletions from the middle in constant time.