#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<iostream.h>
struct node
{
int info;
struct node* link;
};
struct node *last=0;
void main()
{
struct node*first=0;
int n;
clrscr();
struct node* add_first(struct node*);
struct node* add_last(struct node*);
struct node* del_first(struct node*);
struct node* del_last(struct node*);
void traverse(struct node*);
cout<<" \n 1.add at first ";
cout<<" \n 2.add at last ";
cout<<" \n 3.delete at first ";
cout<<" \n 4.delete at last ";
cout<<" \n 5.traverse ";
do
{
cout<<"\n enter your choice ";
cin>>n;
switch(n)
{
case 1:first=add_first(first);
break;
case 2:first=add_last(first);
break;
case 3:first=del_first(first);
break;
case 4:first=del_last(first);
break;
case 5:traverse(first);
break;
default: cout<<"\n\n invalid entry ";
exit(0);
}
} while(n!=0);
getch();
}
struct node *add_first(struct node *f)
{
struct node* nw;
nw=(struct node*)malloc(sizeof(struct node));
cout<<"\n enter the value of node ";
cin>>nw->info;
if(f==0)
{
last=nw;
nw->link=nw;
return(nw);
}
else
{
nw->link=f;
f=nw;
last->link=nw;
return(f);
}
}
struct node* add_last(struct node *f)
{
struct node* nw;
nw=(struct node*)malloc(sizeof(struct node));
cout<<"\n enter the value of node ";
cin>>nw->info;
if(f==0)
{
nw->link=nw;
last=nw;
return(nw);
}
else
{
last->link=nw;
nw->link=f;
last=nw;
return(f);
}
}
struct node* del_first(struct node *f)
{
if(f==0)
{
cout<<"\n list is empty";
return(f);
}
else
{
f=f->link;
last->link=f;
cout<<"\n node is deleted ";
return(f);
}
}
struct node* del_last(struct node* f)
{
if(f==0)
{
cout<<" \n link list is empty ";
return(f);
}
else
{
struct node* save=f;
while(save->link!=last)
{
save=save->link;
save->link=f;
last=save;
cout<<"\n node is deleted ";
return(f);
}
}
}
void traverse(struct node* f)
{
if(f==0)
{
cout<<"link list is empty ";
}
else
{
struct node* save;
cout<<"\n\n";
while(save->link!=f)
{
cout<<save->info<<" ";
save=save->link;
}
cout<<save->info<<"\n\n";
}
}
c programming examples for code writers
c sample code Square Root of a number by using simple calculations