Friday, September 5, 2008

C code to demonstrate operations on stack

#include
#include
#include


struct node
{
int info;
struct node *link;
};
typedef struct node *NODE;

NODE getnode()
{
NODE x;

x=(NODE) malloc( sizeof( struct node));

if(x==NULL)
{
printf(" Out of memory\n");
exit(0);
}

return x;
}

void freenode(NODE x)
{
free(x);
}






NODE insert_front(int item,NODE first)
{
NODE temp;

temp=getnode();

temp->info=item;
temp->link=first;

return temp;
}

NODE delete_front(NODE first)
{
NODE temp;
if(first==NULL)
{
printf(" list empty");
return first;
}

temp=first;
first=first->link;

printf(" Item deleted=%d\n",temp->info);
freenode(temp);

return first;
}



void display(NODE first)
{
if(first==NULL)
{
printf(" list empty\n");
return;
}

printf(" The contents of list\n");

NODE temp=first;

while(temp!=NULL)
{
printf("%d ",temp->info);
temp=temp->link;
}

}



void main()
{
NODE first=NULL;
int choice,item;

for(;;)
{
printf(" 1.insert front\n2.delete front\n3.display\n4.exit\n");
printf(" Enter choice\n");
scanf(" %d",&choice);

switch(choice)
{
case 1:
printf(" Item:");
scanf(" %d",&item);
first=insert_front(item,first);
break;
case 2:
first=delete_front(first);
break;
case 3:
display(first);
break;
default:
exit(0);
}
}
}

0 comments: