Friday, April 9, 2010

ds - push,pop,peek operation in stack (array implementation)

#include"stdio.h"
#include"conio.h"
#include"alloc.h"
#include"stdlib.h"
#define n 10
struct stack
{
int x[10];
int top;
};
typedef struct stack stack;
void push(stack *,int);
void peek(stack *,int);
void display(stack);
void change(stack *,int,int);
void pop(stack *);
void main()
{
stack s;
clrscr();
s.top=0;
push(&s,2);
push(&s,4);
push(&s,6);
push(&s,8);
display(s);
peek(&s,1);
change(&s,2,3);
display(s);
pop(&s);
display(s);
getch();
}
void push(stack *s,int x)
{
if(s->top==(n-1))
{printf("overflow");
return; }
s->top++;
s->x[s->top]=x;
}
void display(stack s)
{
int i=1;
printf("\n");
while(i<=s.top)
{printf("%d",s.x[i]);
i++;}
}
void pop(stack *s)
{
if((s->top)<0) {
printf("underflow");
return;}
s->x[s->top]=0;
s->top--;
}
void peek(stack *s,int p)
{
if((s->top)-p<0) {
printf(" underflow");
return;}
printf("\n%d",s->x[p]);
}
/* change ith element */
void change(stack *s,int p,int x)
{
if((s->top)-p<0) {
printf(" underflow");
return;}
s->x[p]=x;
}

No comments:

Post a Comment