Sure, here's a Python program using classes and objects to perform the required opera ons on a
singly linked list. The program will include methods to insert a node at the beginning and end, count
the number of nodes, and delete the first and last nodes in the list.
Python Program for Singly Linked List
class Node:
def __init__(self, data):
self.data = data
self.next = None
class SinglyLinkedList:
def __init__(self):
self.head = None
def insert_at_beginning(self, data):
"""Insert a new node at the beginning of the list."""
new_node = Node(data)
new_node.next = self.head
self.head = new_node
def insert_at_end(self, data):
"""Insert a new node at the end of the list."""
new_node = Node(data)
if self.head is None:
self.head = new_node
else:
current = self.head
while current.next:
current = current.next
current.next = new_node
def count_nodes(self):
"""Count the number of nodes in the list."""
count = 0
current = self.head
while current:
count += 1
current = current.next
return count
def delete_first_node(self):
"""Delete the first node in the list."""
if self.head:
self.head = self.head.next
def delete_last_node(self):
"""Delete the last node in the list."""
if self.head is None:
return
if self.head.next is None:
self.head = None
return
current = self.head
while current.next and current.next.next:
current = current.next
current.next = None
def display(self):
"""Display the list."""
current = self.head
while current:
print(current.data, end=" -> ")
current = current.next
print("None")
# Example usage
sll = SinglyLinkedList()
# Insert nodes
sll.insert_at_beginning(10)
sll.insert_at_end(20)
sll.insert_at_end(30)
sll.insert_at_beginning(5)
sll.display() # Output: 5 -> 10 -> 20 -> 30 -> None
# Count nodes
print("Node count:", sll.count_nodes()) # Output: Node count: 4
# Delete first and last nodes
sll.delete_first_node()
sll.display() # Output: 10 -> 20 -> 30 -> None
sll.delete_last_node()
sll.display() # Output: 10 -> 20 -> None
Explana on:
1. Node Class:
o __init__(self, data): Ini alizes a node with data and a next pointer set to None.
2. SinglyLinkedList Class:
o __init__(self): Ini alizes the linked list with an empty head.
o insert_at_beginning(self, data): Creates a new node and inserts it at the beginning of
the list.
o insert_at_end(self, data): Creates a new node and inserts it at the end of the list.
o count_nodes(self): Counts and returns the number of nodes in the list.
o delete_first_node(self): Deletes the first node in the list.
o delete_last_node(self): Deletes the last node in the list.
o display(self): Displays the en re list in a readable format.
Usage Example:
The example usage demonstrates inser ng nodes at the beginning and end, coun ng nodes,
and dele ng the first and last nodes. It also shows how to display the list at different stages.
Feel free to test and modify the program as needed! If you have any ques ons or need further
assistance, let me know.