Pages

Friday, January 7, 2011

Stack : Source Code

#include

#include

#include

struct stack
{
int data;

stack *next;

}*top; // top will point to the first node of the stack

void main()
{
top=NULL;
void push();
void pop();
void display();
int c;
do
{
printf("\nStack Operations");
printf("\n1. Push (add) ");
printf("\n2. Display");
printf("\n3. Pop (remove)");
printf("\n4. Exit");
printf("\nSelect your choice ");
scanf("%d",&c);
if(c==1)
push();
else if(c==2)
display();
else if(c==3)
pop();
}while(c!=4);
}
void push()
{
stack *s;
s=(stack *)malloc(sizeof(stack));
printf("\nEnter data ");
scanf("%d",&s->data);
if(top==NULL)
{
top=s; // pushing node to the stack
s->;next=NULL;
}
else
{
s->;next=top;
top=s;
}

printf("\nNode Pushed...");
}

void display()
{
stack *ptr;
for(ptr=top;(ptr);ptr=ptr->next)
{
printf("\n%d",ptr->data);
}
}

void pop()
{
stack *temp;
if(top==NULL)
{
printf("\nStack Underflow(no values found)");
return;
}
else
{
temp=top;
top=top->next;
printf("\nPopped Value : %d",temp->data);
free(temp);
}

}

0 comments:

Post a Comment