Friday, August 27, 2010

C Program to implement stack as an array


#include<stdio.h>
#include<conio.h>
#define ARR 10

struct stack
{
int a[ARR];
int top;
};

void init(struct stack*);
void push(struct stack*,int,int);
int pop(struct stack*);
void main()
{
struct stack s;
int i;
clrscr();
init(&s);

push(&s,8);
push(&s,20);
push(&s,-4);
push(&s,15);
push(&s,18);


i=pop(&s);
printf("\n\n Item popped : %d",i);


i=pop(&s);
printf("\n\n Item popped : %d",i);

i=pop(&s);
printf("\n\n Item popped : %d",i);

getch();
}


/* Initializes the Stack */
void init(struct stack *s)
{
  s->top=-1;
}


/*Add an element to the Stack */
void push(struct stack *s,int item)
{
if(s->top==ARR-1)
{
printf("\n Stack is Full ");
return;
}

s->top++;
s->a[s->top]=item;
}


/* Removes an element from the stack */
int pop(struct stack *s)
{
int data;


if(s->top==-1)
{
printf(" Stack is Empty ");
return NULL;
}


data=s->a[s->top];
s->top--;
return data;
}





No comments:

Post a Comment