public class SinglyLinkedList {
// Node class representing each element in the linked list
class Node {
int data;
Node next;
// Constructor to initialize the node with data
Node(int data) {
this.data = data;
this.next = null;
// Head node of the linked list
private Node head;
// Constructor to initialize the linked list
public SinglyLinkedList() {
head = null;
// Method to insert a node at the start of the linked list
public void insertAtStart(int data) {
Node newNode = new Node(data);
newNode.next = head;
head = newNode;
// Method to insert a node at the end of the linked list
public void insertAtEnd(int data) {
Node newNode = new Node(data);
if (head == null) {
head = newNode;
} else {
Node temp = head;
while (temp.next != null) {
temp = temp.next;
temp.next = newNode;
// Method to delete the node at the start of the linked list
public void deleteAtStart() {
if (head == null) {
System.out.println("Linked list does not exist");
} else {
head = head.next;
// Method to delete the node at the end of the linked list
public void deleteAtEnd() {
if (head == null) {
System.out.println("Linked list does not exist");
} else if (head.next == null) { // Only one element
head = null;
} else {
Node temp = head;
while (temp.next.next != null) {
temp = temp.next;
temp.next = null;
// Method to print the linked list
public void printList() {
Node temp = head;
while (temp != null) {
System.out.print(temp.data + " -> ");
temp = temp.next;
System.out.println("null");
// Main method to demonstrate the singly linked list operations
public static void main(String[] args) {
SinglyLinkedList list = new SinglyLinkedList();
System.out.println("Insertion at start:");
list.insertAtStart(50);
list.insertAtStart(40);
list.insertAtStart(30);
list.insertAtStart(20);
list.insertAtStart(10);
list.printList();
System.out.println("Insertion at end:");
list.insertAtEnd(60);
list.insertAtEnd(70);
list.insertAtEnd(80);
list.insertAtEnd(90);
list.insertAtEnd(100);
list.printList();
System.out.println("Deletion at start:");
list.deleteAtStart();
list.printList();
System.out.println("Deletion at end:");
list.deleteAtEnd();
list.printList();