Stack Implementation Using Array
Implementing stack operations using a Array
Implementation
1
Initialize Stack
- Create a structure stack that holds an integer array (
arr[MAX]
) and an integer top that tracks the top of the stack. - Set the top to
-1
, which indicates that the stack is initially empty.
2
Check if Stack is Full
- If top equals
MAX - 1
(the last index of the array), the stack is full. - Return TRUE if full, otherwise return FALSE.
3
Check if Stack is Empty
- If top equals
-1
, the stack is empty. - Return TRUE if empty, otherwise return FALSE.
4
Push Operation
- First, check if the stack is full by calling the
isFull()
function. - If the stack is full, print Stack Overflow.
- If not, increment the top by
1
and insert the new element atarr[top]
.
5
Pop Operation
- First, check if the stack is empty by calling the
isEmpty()
function. - If the stack is empty, print Stack Underflow and return
-1
. - If not, return the value at
arr[top]
and then decrement top by1
.
Coding Implementation
// stackimplementaionusingarry.c
#include<stdio.h>
#define MAX 100
#define TRUE 1
#define FALSE 0
struct stack{
int top;
int arr[MAX];
};
int isFull(struct stack *st){
return (st->top==MAX-1)?TRUE:FALSE;
}
int isEmpty(struct stack *st){
return(st->top==-1)?TRUE:FALSE;
}
void push(struct stack *st,int element){
if(isFull(st)){
printf("Stack Overflow");
}
else{
st->arr[++st->top]=element;
printf("%d was pushed\n",st->arr[st->top]);
}
}
int pop(struct stack *st){
if(isEmpty(st)){
printf("Stack Underflow");
return -1;
}
else{
return st->arr[st->top--];
}
}
int main(){
struct stack s;
s.top=-1;
push(&s,1);
push(&s,2);
printf("%d was popped\n",pop(&s));
}