Experiment-6
Write a menu driven program to implement following operations on the singly linked list
a) Delete a first node of the linked list
b) Delete a node before specified position
c) Delete a node after specified position
#include <iostream>
using namespace std;
struct Node {
int data;
Node* next;
Node(int value) : data(value), next(nullptr) {}
};
void displayList(Node* head) {
Node* temp = head;
while (temp != nullptr) {
cout << temp->data << " -> ";
temp = temp->next;
cout << "NULL" << endl;
Node* deleteFirstNode(Node* head) {
if (head == nullptr) {
cout << "List is already empty." << endl;
return nullptr;
Node* temp = head;
head = head->next;
delete temp;
cout << "First node deleted." << endl;
return head;
Node* deleteBeforePosition(Node* head, int pos) {
if (pos <= 2 || head == nullptr || head->next == nullptr) {
cout << "Invalid position or insufficient nodes." << endl;
return head;
Node* temp = head;
Node* prev = nullptr;
while (pos > 3 && temp->next->next != nullptr) {
prev = temp;
temp = temp->next;
pos--;
if (prev == nullptr) {
head = head->next;
} else {
prev->next = temp->next;
delete temp;
cout << "Node before position " << pos << " deleted." << endl;
return head;
void deleteAfterPosition(Node* head, int pos) {
Node* temp = head;
while (pos > 1 && temp != nullptr) {
temp = temp->next;
pos--;
}
if (temp == nullptr || temp->next == nullptr) {
cout << "Invalid position or no node exists after it." << endl;
return;
Node* toDelete = temp->next;
temp->next = toDelete->next;
delete toDelete;
cout << "Node after position " << pos << " deleted." << endl;
int main() {
Node* head = new Node(10);
head->next = new Node(20);
head->next->next = new Node(30);
head->next->next->next = new Node(40);
int choice, pos;
do {
cout << "\nMenu:\n";
cout << "1. Delete the first node\n";
cout << "2. Delete the node before a specified position\n";
cout << "3. Delete the node after a specified position\n";
cout << "4. Display the linked list\n";
cout << "5. Exit\n";
cout << "Enter your choice: ";
cin >> choice;
switch (choice) {
case 1:
head = deleteFirstNode(head);
break;
case 2:
cout << "Enter the position: ";
cin >> pos;
head = deleteBeforePosition(head, pos);
break;
case 3:
cout << "Enter the position: ";
cin >> pos;
deleteAfterPosition(head, pos);
break;
case 4:
cout << "Linked list: ";
displayList(head);
break;
case 5:
cout << "Exiting program.\n";
break;
default:
cout << "Invalid choice. Try again.\n";
} while (choice != 5);
while (head != nullptr) {
Node* temp = head;
head = head->next;
delete temp;
return 0;