In this post, we will implement the stack using structure. First we define a Stack using structure as below:
struct Stack{
int top;
int elements[MAX];
};
In the above code top
hold the value of top of stack and elements
array is used to store the stack elements and MAX
is the maximum number of element that the stack can hold before overflowing. Push Operation:
Now we will implement the push operation on the stack above defined. Let us see the code for push operation:
void push(struct Stack *s, int item){
if(s->top == MAX-1){
printf("Stack Overflow\n");
}
else{
s->elements[++(s->top)] = item;
}
}
Pop Operation:
Now we will implement the pop operation on the stack above defined. Let us see the code for push operation:
int pop(struct Stack *s){
if(s->top == -1){
printf("Stack Underflow\n");
}
else{
return s->elements[(s->top)--];
}
}
Program to implement stack using structure:
Here is the complete implementation of stack using structure:
#include <stdio.h>
#define MAX 10
struct Stack{
int top;
int elements[MAX];
};
void push(struct Stack *, int);
int pop(struct Stack *);
void display(struct Stack *);
int main(){
struct Stack s;
s.top = -1;
push(&s, 1);
push(&s, 2);
display(&s);
pop(&s);
display(&s);
return 0;
}
void push(struct Stack *s, int item){
if(s->top == MAX-1){
printf("Stack Overflow\n");
}
else{
s->elements[++(s->top)] = item;
}
}
int pop(struct Stack *s){
if(s->top == -1){
printf("Stack Underflow\n");
}
else{
return s->elements[(s->top)--];
}
}
void display(struct Stack *s){
printf("The elements of Stack: ");
for( int i = 0; i <= s->top; i++ ){
printf("%d ", s->elements[i]);
}
printf("\n");
}
Comments
Post a Comment