DS Lab Assignment2
DS Lab Assignment2
CODE
class Node:
"""A class to represent a node in a doubly linked list."""
def __init__(self, data):
self.data = data
self.next = None
self.prev = None
class DoublyLinkedList:
"""A class to represent a doubly linked list."""
def __init__(self):
self.head = None
self.tail = None
def remove_from_beginning(self):
"""Remove an element from the beginning of the doubly linked
list."""
if self.head is None: # List is empty
print("List is empty! Nothing to remove.")
return
removed_data = self.head.data
if self.head == self.tail: # Single element in the list
self.head = self.tail = None
else:
self.head = self.head.next
self.head.prev = None
print(f"Removed {removed_data} from the beginning.")
def remove_from_end(self):
"""Remove an element from the end of the doubly linked list."""
if self.tail is None: # List is empty
print("List is empty! Nothing to remove.")
return
removed_data = self.tail.data
if self.head == self.tail: # Single element in the list
self.head = self.tail = None
else:
self.tail = self.tail.prev
self.tail.next = None
print(f"Removed {removed_data} from the end.")
def display(self):
"""Display the elements of the doubly linked list."""
if self.head is None:
print("The list is empty.")
return
elements = []
current = self.head
while current is not None:
elements.append(current.data)
current = current.next
print("List:", " <-> ".join(map(str, elements)))
OUTPUT