Linear Linked List - All Operations Included
Linear Linked List - All Operations Included
struct Node {
int data;
Node* next;
Node(int val) : data(val), next(nullptr) {}
};
class LinkedList {
private:
Node* head;
public:
LinkedList() : head(nullptr) {}
void removeFromHead() {
if (!head) return;
Node* temp = head;
head = head->next;
delete temp;
}
void removeFromTail() {
if (!head) return;
if (!head->next) {
delete head;
head = nullptr;
return;
}
Node* temp = head;
while (temp->next->next) {
temp = temp->next;
}
delete temp->next;
temp->next = nullptr;
}
void removeFromMiddle(int position) {
if (!head) return;
Node* temp = head;
int count = 1;
while (count < position - 1 && temp->next) {
temp = temp->next;
count++;
}
if (temp->next) {
Node* toDelete = temp->next;
temp->next = temp->next->next;
delete toDelete;
}
}
void display() {
Node* temp = head;
while (temp) {
cout << temp->data << " ";
temp = temp->next;
}
cout << endl;
}
~LinkedList() {
Node* temp = head;
while (temp) {
Node* toDelete = temp;
temp = temp->next;
delete toDelete;
}
}
};
int main() {
LinkedList list;
int choice, value, position;
do {
cout << "\n1. Insert at Head\n";
cout << "2. Insert at Tail\n";
cout << "3. Insert at Middle\n";
cout << "4. Remove from Head\n";
cout << "5. Remove from Tail\n";
cout << "6. Remove from Middle\n";
cout << "7. Display\n";
cout << "8. Exit\n";
cout << "Enter your choice: ";
cin >> choice;
switch (choice) {
case 1:
cout << "Enter value to insert at head: ";
cin >> value;
list.insertAtHead(value);
break;
case 2:
cout << "Enter value to insert at tail: ";
cin >> value;
list.insertAtTail(value);
break;
case 3:
cout << "Enter value to insert: ";
cin >> value;
cout << "Enter position to insert: ";
cin >> position;
list.insertAtMiddle(value, position);
break;
case 4:
list.removeFromHead();
break;
case 5:
list.removeFromTail();
break;
case 6:
cout << "Enter position to remove: ";
cin >> position;
list.removeFromMiddle(position);
break;
case 7:
cout << "Linked List: ";
list.display();
break;
case 8:
cout << "Exiting program.\n";
break;
default:
cout << "Invalid choice! Please try again.\n";
}
return 0;
}