0% found this document useful (0 votes)
14 views3 pages

Code

The document defines a LinkedList class with methods to insert nodes at the beginning, middle, or end of the list. It also includes a printList method. The main function tests the LinkedList class with a menu-driven program that allows the user to insert nodes into different positions and print the list.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views3 pages

Code

The document defines a LinkedList class with methods to insert nodes at the beginning, middle, or end of the list. It also includes a printList method. The main function tests the LinkedList class with a menu-driven program that allows the user to insert nodes into different positions and print the list.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 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