You are on page 1of 4

#include <iostream>

using namespace std;

// Define a structure for a node in the linked list


struct Node {
int data;
Node* next;
};

// Function to create a new node


Node* createNode(int data) {
Node* newNode = new Node;
newNode->data = data;
newNode->next = nullptr;
return newNode;
}

// Function to insert a node at the beginning of the linked list


Node* insertNode(Node* head, int data) {
Node* newNode = createNode(data);
newNode->next = head;
return newNode;
}

// Function to delete a node with given data from the linked list
Node* deleteNode(Node* head, int data) {
Node* prev = nullptr;
Node* curr = head;

// If head node holds the data to be deleted


if (curr != nullptr && curr->data == data) {
head = curr->next;
delete curr;
return head;
}

// Find the node to be deleted


while (curr != nullptr && curr->data != data) {
prev = curr;
curr = curr->next;
}
// If the data was not found in the list
if (curr == nullptr) {
cout << "Element not found in the list." << endl;
return head;
}

// Unlink the node from the linked list


prev->next = curr->next;
delete curr;
return head;
}

// Function to search for a node with given data


bool searchNode(Node* head, int data) {
Node* temp = head;
while (temp != nullptr) {
if (temp->data == data)
return true;
temp = temp->next;
}
return false;
}

// Function to display all elements in the linked list


void displayList(Node* head) {
Node* temp = head;
while (temp != nullptr) {
cout << temp->data << " ";
temp = temp->next;
}
cout << endl;
}

int main() {
Node* head = nullptr;
int choice, data;

do {
cout << "1. Insert Element" << endl;
cout << "2. Delete Element" << endl;
cout << "3. Search Element" << endl;
cout << "4. Display List" << endl;
cout << "5. Exit" << endl;
cout << "Enter your choice: ";
cin >> choice;

switch (choice) {
case 1:
cout << "Enter element to insert: ";
cin >> data;
head = insertNode(head, data);
break;
case 2:
cout << "Enter element to delete: ";
cin >> data;
head = deleteNode(head, data);
break;
case 3:
cout << "Enter element to search: ";
cin >> data;
if (searchNode(head, data))
cout << "Element found in the list." << endl;
else
cout << "Element not found in the list." << endl;
break;
case 4:
cout << "List elements: ";
displayList(head);
break;
case 5:
cout << "Exiting program..." << endl;
break;
default:
cout << "Invalid choice. Please enter a valid option." << endl;
}
} while (choice != 5);

return 0;
}

You might also like