Tuesday, 25 September 2012

Stack Operation using C Language


Stack......
a stack is an area of memory that holds all local variables and parameters used by any function
One way of describing the stack is as a last in, first out (LIFO)
The push operation adds a new item to the top of the stack, or initializes the stack if it is empty
 If the stack is full and does not contain enough space to accept the given item, the stack is then considered to be in an overflow state. The pop operation removes an item from the top of the stack. A pop either reveals previously concealed items, or results in an empty stack, but if the stack is empty then it goes into underflow state (It means no items are present in stack to be removed)


Stack Operation Using Single Link List 

#include<stdio.h>
#include<conio.h>
typedef struct st_stack
{
int data;
struct st_stack *next;
}stack;
/* Function Prototype */
stack* create(int);
void push(stack**,int);
void pop(stack**);
void print(stack*);
void main()
{
stack *start=NULL;
int n,s,opt;



do
{
clrscr();
printf("\n1. Print\n2. Push\n0. Exit \nEnter your choice>> ");
fflush(stdin);
scanf("%d",&opt);
switch(opt)
{
case 1:
print(start);
getch();
break;

case 2:
printf("Enter Number for add in Stack>> ");
scanf("%d",&n);
push(&start,n);
break;
case 3:
pop(&start);
break;
case 0:
break;
default:
printf("\nInvalid Choice ");
getch();
}
}while(opt!=0);
}



stack * create(int n)
{
stack *nw;
nw=(stack*) malloc(sizeof(stack));
nw->data=n;
nw->next=NULL;
return(nw);
}
void push(stack **st,int n)
{
stack *nw=create(n);
if(*st==NULL)
{
*st=nw;
}
else
{
nw->next=*st;
*st=nw;
}

}
void pop(stack **st)
{
stack *pt;
if(*st==NULL)
{
printf("\nStack is empty");
getch();
}
else
{
pt=*st;
*st=(*st)->next;
}
}
void print(stack *st)
{
stack *pt;
for(pt=st;pt!=NULL;pt=pt->next)

printf("[ %d ]",pt->data);

}