Sie sind auf Seite 1von 3

//operations in LInked list C/C++//

#include<iostream.h>
#include<conio.h>
#include<malloc.h>
#include<process.h>
struct node
{
int info;
struct node *next;
};
struct node *list=NULL;
struct node* getnode()
{
struct node *ptr;
ptr=(node*)malloc(sizeof(node));
return ptr;
}

void insert_at_end(int x)
{
struct node *temp,*r;
temp=getnode();
temp->info=x;
r=list;
if(list==NULL)
{
list=temp;
list->next=NULL;
}
else
{
while(r->next!=NULL)
r=r->next;
temp->next=NULL;
r->next=temp;
}
}
void insert_at_beg(int x)
{
struct node *p;
p=getnode();
p->info=x;
if(list==NULL)
{
list=p;
list->next=NULL;
}
else
{
p->next=list;
list=p;
}
}
void delete_at_beg()
{
struct node *temp=list;
if(list==NULL)
{
cout<<"no item to delete"<<endl;
}
else
{
cout<<"deleted item:: "<<temp->info;
list=temp->next;
free(temp);
}
}
void display()
{
node *temp = list;
do
{ if (temp== NULL)
cout << "End of list" << endl;
else
{ // Display details for what temp points to
cout <<temp->info << endl;
temp = temp->next;
}
}
while (temp != NULL);
}
void delete_at_end()
{
if(list==NULL)
{
cout<<"unable to delete"<<endl;
}
else
{
struct node *temp,*p;
temp=list;
while(temp->next!=NULL)
{
p=temp;
temp=temp->next;
}
p->next=NULL;
free(temp);
}
}

void main()
{
int a,cs;
while(1)
{
cout<<"1. Add at end\n2. Add at beg \n3. Display \n4. Delete at beg\n5. Detete
at end\n6. Exit\n"<<endl;
cin>>cs;
switch(cs)
{
case 1:
clrscr();
cout<<"----------------------------------"<<endl;
cout<<"enter the value to insert at end of the node"<<endl;
cin>>a;
insert_at_end(a);
cout<<"----------------------------------"<<endl;
break;
case 2:
clrscr();
cout<<"----------------------------------"<<endl;
cout<<"enter the value to insert at begining of the node"<<endl;
cin>>a;
insert_at_beg(a);
cout<<"----------------------------------"<<endl;
break;
case 3:
clrscr();
cout<<endl<<"----------------------------------"<<endl;
display();
cout<<endl<<"----------------------------------"<<endl;
break;
case 4:
clrscr();
cout<<"----------------------------------"<<endl;
delete_at_beg();
cout<<"----------------------------------"<<endl;
break;
case 5:
clrscr();
cout<<"----------------------------------"<<endl;
delete_at_end();
cout<<"----------------------------------"<<endl;
break;
case 6:
exit(0);
}
}
getch();
}

Das könnte Ihnen auch gefallen