struct Stack { //Declation of Stack
int size;
int top;
int* arr;
};
struct Stack S; //Implementing the Stack
S.size = 10;
S.top = -1;
S.arr = (int*)malloc(S.size*sizeof(int)); //Creating array dynamically
int isEmpty(struct Stack *ptr)
{
if(ptr->top==-1)
{
return 1; //if top value is -1 then stack is empty return true
}
else {
return 0
}
}
int isFull(struct Stack *ptr)
{
if(ptr->top == ptr->size-1)
{
return 1; // if top value is equal to size of the stack then stack is full
}
else
{
return 0;
}
}
void push(struct Stack *ptr,int value)
{
if(isFull(ptr))
{
printf("Stack Overflow! ");
}
else
{
ptr->top++;
ptr->arr[ptr->top] = value; // The next element is assigned to top
}// take the value to next element of stack
}
int pop(struct stack *ptr)
{
if(isEmpty(ptr))
{
printf("Stack Underflow!");
return 0;
}
else
{
int val = arr[ptr->top]; // accessing top element
ptr->top--;
return val;
}
}
int peek(struct Stack *ptr,int pos)
{
int arrnum = top-pos+1; //index of the array to be stored
if(arrnum<0)
{
printf("Not a valid position for insert a value");
return 0;
}
else
{
return ptr->arr[arrnum];
}
}
@Peek Operation in Stack Using Arrays (With C Code & Explanation) | CodeWithHarry