DS Lab Assignment1
DS Lab Assignment1
CODE
class Node:
"""A class to represent a node in a singly linked list."""
def __init__(self, data):
self.data = data
self.next = None
class SinglyLinkedList:
"""A class to represent a singly linked list."""
def __init__(self):
self.head = None
new_node = Node(x)
if position == 0:
new_node.next = self.head
self.head = new_node
print(f"Inserted {x} at position {position}.")
return
current = self.head
count = 0
while current is not None and count < position - 1:
current = current.next
count += 1
if current is None:
print(f"Position {position} is out of bounds.")
else:
new_node.next = current.next
current.next = new_node
print(f"Inserted {x} at position {position}.")
def remove_from_beginning(self):
"""Remove an element from the beginning of the list."""
if self.head is None:
print("List is empty! Nothing to remove.")
return
removed_data = self.head.data
self.head = self.head.next
print(f"Removed {removed_data} from the beginning.")
if position == 0:
removed_data = self.head.data
self.head = self.head.next
print(f"Removed {removed_data} from position {position}.")
return
current = self.head
count = 0
while current.next is not None and count < position - 1:
current = current.next
count += 1
if current.next is None:
print(f"Position {position} is out of bounds.")
else:
removed_data = current.next.data
current.next = current.next.next
print(f"Removed {removed_data} from position {position}.")
def display(self):
"""Display the elements of the 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