#include <bits/stdc++.
h>
using namespace std;
struct Node {
int data;
Node* next;
Node(int x) : data(x), next(nullptr) {}
};
class SinglyLinkedList {
private:
Node* head;
public:
SinglyLinkedList() : head(nullptr) {}
// Traverse
void traverse() {
if (!head) { cout << "List empty\n"; return; }
Node* cur = head;
while (cur) {
cout << cur->data << (cur->next ? " -> " : "\n");
cur = cur->next;
// Insert at beginning
void insertAtBeg(int x) {
Node* n = new Node(x);
n->next = head;
head = n;
}
// Insert at ith position (1-based index)
bool insertAtPos(int x, int pos) {
if (pos < 1) return false;
if (pos == 1) { insertAtBeg(x); return true; }
Node* cur = head;
for (int i = 1; cur && i < pos - 1; i++) cur = cur->next;
if (!cur) return false; // invalid pos
Node* n = new Node(x);
n->next = cur->next;
cur->next = n;
return true;
// Remove from beginning
bool removeAtBeg() {
if (!head) return false;
Node* tmp = head;
head = head->next;
delete tmp;
return true;
// Remove from ith position
bool removeAtPos(int pos) {
if (!head || pos < 1) return false;
if (pos == 1) return removeAtBeg();
Node* cur = head;
for (int i = 1; cur && i < pos - 1; i++) cur = cur->next;
if (!cur || !cur->next) return false;
Node* tmp = cur->next;
cur->next = tmp->next;
delete tmp;
return true;
// Search for element x and return its pointer
Node* search(int x) {
Node* cur = head;
while (cur) {
if (cur->data == x) return cur;
cur = cur->next;
return nullptr;
};
// ---------------- MAIN ----------------
int main() {
SinglyLinkedList sll;
int choice, x, pos;
do {
cout << "\n--- Singly Linked List Menu ---\n";
cout << "1. Insert at beginning\n";
cout << "2. Insert at position i\n";
cout << "3. Remove at beginning\n";
cout << "4. Remove at position i\n";
cout << "5. Search for element x\n";
cout << "6. Traverse\n";
cout << "0. Exit\n";
cout << "Enter choice: ";
cin >> choice;
switch(choice) {
case 1:
cout << "Enter value: "; cin >> x;
sll.insertAtBeg(x);
break;
case 2:
cout << "Enter value and position: "; cin >> x >> pos;
if (sll.insertAtPos(x,pos)) cout << "Inserted\n"; else cout << "Invalid position\n";
break;
case 3:
if (sll.removeAtBeg()) cout << "Deleted\n"; else cout << "List empty\n";
break;
case 4:
cout << "Enter position: "; cin >> pos;
if (sll.removeAtPos(pos)) cout << "Deleted\n"; else cout << "Invalid position\n";
break;
case 5:
cout << "Enter value: "; cin >> x;
Node* res = sll.search(x);
if (res) cout << "Found element " << res->data << " at address " << res << "\n";
else cout << "Not found\n";
break;
case 6:
sll.traverse();
break;
case 0:
cout << "Exiting...\n";
break;
default:
cout << "Invalid choice\n";
} while(choice != 0);
return 0;