Friday, April 17, 2009

STACK USING LINKED LIST

/*stack using linked list*/
#include
#include
#include
struct node
{
int data;
struct node *ptr;
};
typedef struct node NODE;
NODE *top=NULL,*nn,*temp;
main()
{
int ch,rpt=1;
clrscr();
while(rpt)
{
printf("1.push\n");
printf("2.pop\n");
printf("3.display\n");
printf("4.exit\n");
printf("enter your choice\n");
scanf("%d",&ch);
switch(ch)
{
case 1:push();
break;
case 2:pop();
break;
case 3:display();
break;
case 4:return;
}
printf("\nDo you want to continue press 1 for yes and 0 for no\n");
scanf("%d",&rpt);
}
}

push()
{
int num;
printf("enter the element to be inserted\n");
scanf("%d",&num);
nn=(NODE*)malloc(sizeof(NODE));
nn->data=num;
if(top==NULL)
{
nn->ptr=NULL;
top=nn;
}
else
{
nn->ptr=top;
top=nn;
}
}

pop()
{
if(top==NULL)
printf("stack is empty\n");
else
{
temp=top;
printf("Deleted element=%d",temp->data);
top=top->ptr;
free(temp);
}
}

display()
{
if(top==NULL)
printf("empty list\n");
else
{
printf("status of the stack is\n");
temp=top;
while(temp!=NULL)
{
printf("%d\n",temp->data);
temp=temp->ptr;
}
}
}

No comments: