Saturday, 30 May 2020

complete linked list all possible operations in one in C++ using structure

//linked list
#include<iostream>
using namespace std;
void first();// for creating 1st node
void create();// for creating a node
void show();// for display nodes
void insert();// for inserting nodes at diff pos

void gpos();
void last();

void del(); //for deleting node
int count=0;// for counting of nodes
struct node
{
int data;
node*next;
};
struct node* start;
struct node* ptr1;

int main()
{
node s;
create();
int choice;
while(1)
{
cout<<"\n\n\n\t\t\t******MENU********";
cout<<"\n 1 insert\n 2 delete \n 3 DISPLAY\n 4 EXIT \n 5 no of nodes\n";
cin>>choice;
switch(choice)
{
case 1:insert();
break;
case 2:del();
break;
case 3:show();
break;
case 4: exit(0)  ;
break;
case 5:cout<<count;
break;
default: cout<<" wrong  choice\n:";
break;
}
}

return 0;    // getch();
}
void create()
{
// it will create 1st node
int value;
start=NULL;
ptr1=new node;

cout<<"enter to insert in 1st node\n";
cin>>value;
ptr1->data=value;
ptr1->next=NULL;
start=ptr1;
cout<<"created successfully\n";
count++;
}
void insert()
{

int pos;
cout<<"\n\nenter the position at which u want to insert\n";
cout<<"1  at first\n";
cout<<"2  at last\n";
cout<<"3  at given position \n";
cin>>pos;
switch(pos)
{
case 1:first();
break;
case 2:last();
break;
case 3:gpos();
break;
default: cout<<"wrong choice";
break;
}
cout<<"node is added successfully!!\n";
count++;
}
void first()
{
node *temp,*ptr3;
       // temp=start;
ptr3=new node;
cout<<"enter data\n";
cin>>ptr3->data;
ptr3->next=start;
start=ptr3;
}


void show()
{
node* temp;
temp=start;
if(temp==NULL)
{
cout<<"empty";
}
       else
{ cout<<"START-->";
while(temp!=NULL)
{
cout<<temp->data<<"-->";
temp=temp->next;
}
cout<<"NULL\n";
}
}

void gpos()
{
node *temp3,*ptr;
ptr=new node;
node *temp4;
temp3=start;
temp4=temp3;
if(temp3==NULL)
{
cout<<"list is empty\n";
}
else
{
int val,ch;
cout<<"enter the pos where element is to be inserted\n";
cin>>ch;
if(ch==1)
{
   first();
}
else
     {
for(int i=1;i<ch;i++)
{
temp4=temp3;
temp3=temp3->next;

}
cout<<"enter the item to inserted\n";
cin>>ptr->data;
ptr->next=temp4->next;
temp4->next=ptr;
}
}
}

void last()
{
node *temp,*temp2,*ptr3;
temp=start;
ptr3=new node;
cout<<"enter data\n";
cin>>ptr3->data;
if(temp==NULL)
{
cout<<"empty";
}
while(temp!=NULL)
{
temp2=temp;
temp=temp->next;
}
ptr3->next=NULL;
temp2->next=ptr3;
}

void del()
{


node *temp3;
node *temp4;
temp3=start;
temp4=temp3;
if(temp3==NULL)
{
cout<<"list is empty\n";
}
else
{
int val,ch;
cout<<"enter the pos of element to delete\n";
cin>>ch;
if(ch==1)
{
val=temp3->data;
   cout<<"deleted item\n"<<val;
   start=start->next;
   count--;
}
else if(ch<=count)
   {
for(int i=1;i<ch;i++)
{
temp4=temp3;
temp3=temp3->next;

}
val=temp3->data;
cout<<" deleted element is"<<val;
temp4->next=temp3->next;
count--;
}
else
{
cout<<"can not delete node because there are only "<<count<<"node\n";
}
}
}

No comments:

Post a Comment