You are on page 1of 3

Code:

ID: 41230100803
#include<bits/stdc++.h>
using namespace std;

class Node {
public:
int data;
Node* next;
};

class LinkedList {
public:
Node* head;
LinkedList() { head = NULL; }

void insertAtBeginning(int data) {


Node* newNode = new Node();
newNode->data = data;
newNode->next = head;
head = newNode;
}

void insertInMiddle(int data, int position) {


Node* newNode = new Node();
newNode->data = data;
Node* temp = head;
for(int i=0; i<position-2; i++) {
temp = temp->next;
}
newNode->next = temp->next;
temp->next = newNode;
}

void insertAtEnd(int data) {


Node* newNode = new Node();
newNode->data = data;
newNode->next = NULL;
if(head == NULL) {
head = newNode;
return;
}
Node* temp = head;
while(temp->next != NULL) {
temp = temp->next;
}
temp->next = newNode;
}

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

int main() {
LinkedList list;
int data, position, choice;

cout << "\t\t| ID: 41230100803 |\n";

do {
cout << "\n1. Insert at the beginning\n2. Insert in the middle\n3. Insert at the end\n4. Print
list\n5. Exit\nEnter your choice: ";
cin >> choice;
switch(choice) {
case 1:
cout << "Enter the data for insert at beginnig: ";
cin >> data;
list.insertAtBeginning(data);
break;
case 2:
cout << "Enter the data for insert at Ending : ";
cin >> data;
cout << "Enter the position for the node to be inserted in the middle: ";
cin >> position;
list.insertInMiddle(data, position);
break;
case 3:
cout << "Enter the data for the node to be inserted at the end: ";
cin >> data;
list.insertAtEnd(data);
break;
case 4:
cout << "List: ";
list.printList();
break;
case 5:
cout << "Exiting...\n";
break;
default:
cout << "Invalid choice! Please enter a valid option.\n";
}
} while(choice != 5);

return 0;
}
Output:

You might also like