PROGRAM8-DSA
PROGRAM8-DSA
AIM : Write a program to implement singly linked list for the following
operations: Create, Display, searching, traversing and deletion.
TOOLS USED : Visual Studio Code Editor
SOURCE CODE:
#include <iostream>
using namespace std;
struct Node {
int data;
Node* next;
Node(int value) : data(value), next(nullptr) {}
};
class LinkedList {
Node* head;
public:
LinkedList() : head(nullptr) {}
void create(int value) {
Node* newNode = new Node(value);
if (!head) head = newNode;
else {
Node* temp = head;
while (temp->next) temp = temp->next;
temp->next = newNode;
}
cout << value << " added.\n";
}
void display() {
if (!head) { cout << "List is empty!\n"; return; }
for (Node* temp = head; temp; temp = temp->next) cout << temp->data << " -> ";
cout << "NULL\n";
}
void search(int value) {
Node* temp = head;
int pos = 1;
while (temp) {
if (temp->data == value) { cout << value << " found at position " << pos << ".\n";
return; }
temp = temp->next; pos++;
}
cout << value << " not found.\n";
}
void deleteNode(int value) {
if (!head) { cout << "List is empty.\n"; return; }
if (head->data == value) {
Node* temp = head;
head = head->next;
delete temp;
cout << value << " deleted.\n";
return; }
Node* temp = head;
while (temp->next && temp->next->data != value) temp = temp->next;
if (!temp->next) { cout << value << " not found.\n"; return; }
Node* toDelete = temp->next;
temp->next = temp->next->next;
delete toDelete;
cout << value << " deleted.\n";
}
void traverse() { display(); }
};
int main() {
LinkedList list;
int choice, value;
do {
cout << "\n1. Create 2. Display 3. Search 4. Delete 5. Exit\nEnter choice: ";
cin >> choice;
if (choice == 1) {
cout << "Enter value: "; cin >> value;
list.create(value);
} else if (choice == 2) list.display();
else if (choice == 3) {
cout << "Enter value to search: "; cin >> value;
list.search(value);
} else if (choice == 4) {
cout << "Enter value to delete: "; cin >> value;
list.deleteNode(value); }
} while (choice != 5);
return 0;
}
OUTPUT:
LEARNING OUTCOMES:
1. Understanding Linked Lists: Learn the fundamental concepts of singly linked lists and
their operations.
2. Dynamic Memory Management: Understand the use of pointers and dynamic memory
allocation with new and delete in C++.
3. Implementation of Operations: Gain hands-on experience in creating, displaying,
searching, traversing, and deleting nodes.