For the given code your task is to write the following functions and make menu to call them in main:
1)Insert_Element_at(int X, int pos),
2)bool Delete_Element(int X)
3) void Empty_List()
class List{
public:
int item;
int pos;
List* nextNode;
List()
{
this->pos=0;
}
List(int pos)
{
this->pos=pos;
}
List(int item,int pos)
{
this->item=item;
this->pos=pos;
}
List(List &list)
{
this->item=list.item;
this->pos=list.pos;
this->nextNode=list.nextNode;
}
};
void Insert_Element(List** head, int data)
{
//code present here to do this
}
#include <iostream>
using namespace std;
class List{
public:
int item;
int pos;
List* nextNode;
List()
{
this->pos=0;
}
List(int pos)
{
this->pos=pos;
}
List(int item,int pos)
{
this->item=item;
this->pos=pos;
}
List(List &list)
{
this->item=list.item;
this->pos=list.pos;
this->nextNode=list.nextNode;
}
};
List * headNode = NULL;
void Insert_Element(List** head, int data)
{
List* newNode = new List();
newNode->item = data;
newNode->nextNode = (*head);
(*head) = newNode;
}
void print(List * node){
List * list = node;
while(list != NULL){
cout<<list->item<<" ";
list = list->nextNode;
}
}
void delete_node(List **head, int key){
List* temp = *head;
List* prevNode = NULL;
if(temp !=NULL && temp->item){
*head = temp->nextNode;
delete temp;
return;
}
else{
while(temp != NULL && temp->item != key){
prevNode = temp;
temp = temp->nextNode;
}
if(temp==NULL)
return;
prevNode->nextNode = temp->nextNode;
delete temp;
}
}
void Empty_List(){
headNode = NULL;
}
int main(){
List * list = NULL;
Insert_Element(&headNode, 4);
Insert_Element(&headNode, 5);
Insert_Element(&headNode, 6);
Insert_Element(&headNode, 7);
Insert_Element(&headNode, 8);
int choice;
do{
cout<<"\nSelect an option\n1. Insert an element into the linked list\n2.Display the content of the linked list.\n3. Delete element.\n";
cout<<"4. Make the list empty.\n0. Exit the program\n";
cin>>choice;
if(choice==1){
cout<<"Enter the item\n";
int item;
cin>>item;
Insert_Element(&headNode, item);
}
else if(choice == 2){
print(headNode);
}
else if(choice==3){
cout<<"Enter the item\n";
int item;
cin>>item;
Insert_Element(&headNode, item);
delete_node(&headNode, item);
}
else if(choice == 4){
Empty_List();
print(headNode);
}
}while(choice !=0);
cout<<"Terminated successfully\n";
}
Comments
Leave a comment