Friday, May 28, 2010
two way linked list
#include
#include
struct node
{
int data;
struct node *next;
struct node *prev;
}*start,*last,*newnode,*p,*ptr;
void main()
{
int ch;
clrscr();
do
{
printf("**********MAIN MENU***********");
printf("\n1.add start");
printf("\n2.add middle");
printf("\n3.addlast");
printf("\n4.delete");
printf("\n5.show");
printf("\n6.count");
printf("\n7.search");
printf("\n8.sort");
printf("\n9.reverse");
printf("\n0.exit");
printf("\nenter your choice");
scanf("%d",&ch);
switch(ch)
{
case 1 : addstart();break;
case 2 : addmiddle();break;
case 3 : addlast();break;
case 4 : deldata();break;
case 5 : show();break;
case 6 : count();break;
case 7 : search();break;
case 8 : sort();break;
case 9 : reverse(); break;
case 0 : break;
default:printf("wrong choice");break;
}
}while(ch!=0);
}
addstart()
{
struct node *newnode;
newnode=(struct node*)malloc(sizeof(struct node));
printf("enter the data");
scanf("%d",&newnode->data);
newnode->next=NULL;
newnode->prev=NULL;
if(start==NULL)
{
start=newnode;
last=newnode;
}
else
{
start->prev=newnode;
newnode->next=start;
start=newnode;
}
}
addlast()
{
struct node *newnode;
newnode=(struct node*)malloc(sizeof(struct node));
printf("enter the data");
scanf("%d",&newnode->data);
newnode->next=NULL;
newnode->prev=NULL;
if(start==NULL)
{
start=newnode;
last=newnode;
}
else
{
last->next=newnode;
newnode->prev=last;
last=newnode;
}
}
show()
{
for(p=start;p!=NULL;p=p->next)
{
printf("%d",p->data);
}
}
count()
{
int c=0;
for(p=start;p!=NULL;p=p->next)
{
c++;
}
printf("%d",c);
}
addmiddle()
{
int n;
struct node *newnode;
newnode=(struct node*)malloc(sizeof(struct node));
printf("enter the data");
scanf("%d",&newnode->data);
newnode->next=NULL;
newnode->prev=NULL;
if(start==NULL)
{
start=newnode;
last=newnode;
}
else
{
printf("enter data after which u want to add");
scanf("%d",&n);
for(p=start;p!=NULL;p=p->next)
{
if(p->data==n)
{
p->next->prev=newnode;
newnode->next=p->next;
newnode->prev=p;
p->next=newnode;
break;
}
}
}
}
search()
{
int n,flag=0,c=0;
printf("enter data to search");
scanf("%d",&n);
for(p=start;p!=NULL;p=p->next)
{
if(p->data==n)
{
flag=1;
c++;
break;
}
else
c++;
}
if(flag==1)
printf("found on %d",c);
else
printf("not found");
}
deldata()
{
int n;
printf("enter no to delete");
scanf("%d",&n);
if(start==NULL)
{
printf("no data to delete");
}
else
{
for(p=ptr=start;p!=NULL;p=p->next)
{
if(p->data==n)
{
if(p==start)
{
start=p->next;
start->prev=NULL;
free(p);
break;
}
else if(p==last)
{
last=p->prev;
last->next=NULL;
free(p);
break;
}
else
{
p->next->prev=p->prev;
p->prev->next=p->next;
free(p);
break;
}
}
}
}
}
sort()
{
int t;
p=start;
do
{
ptr=start;
do
{
if(ptr->data>ptr->next->data)
{
t=ptr->data;
ptr->data=ptr->next->data;
ptr->next->data=t;
}
ptr=ptr->next;
}while(ptr->next!=NULL);
p=p->next;
}while(p!=NULL);
}
reverse()
{
for(p=last;p!=NULL;p=p->prev)
{
printf("%d",p->data);
}
}
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment