Stack & Its Implementation
- abhijitsathe
- Nov 7
- 2 min read
Q.1) Define Stack.
Stack is an ordered collection of elements into which new element can be inserted or existing element can be deleted from one end called as the top of the stack.
Stack is a Last-in-First-Out (LIFO) or First-In-Last-Out (FILO) structure.
Q.2) What are the application of Stack?
Q.3) "Stack can be considered as a priority queue.". Comment.
Stack can be considered as an Ascending Priority Queue with minimal waiting time before popping an element as it is Last-In-First-Out (LIFO) structure.
Stack can be considered as a Descending Priority Queue as elements are popped as per latest time of insertion.
Q.4) Write a C program to implement Stack using array. (Static Stack)
#include <stdio.h>
#include <stdlib.h>
#define MAXSZ 10
struct stack
{
int data[MAXSZ];
int top;
};
void initstack(struct stack *s)
{
s->top = -1;
}
int isFull(struct stack *s)
{
return s->top == MAXSZ-1;
}
void push(struct stack *s, int value)
{
if (isFull(s))
{
printf("Stack Overflow !!!");
exit(1);
}
s->data[++s->top] = value;
}
int isEmpty(struct stack *s)
{
return s->top == -1;
}
int pop(struct stack *s)
{
if (isEmpty(s))
{
printf("Stack Underflow !!!");
exit(1);
}
return s->data[s->top--];
}
int stacktop(struct stack *s) /*peek*/
{
if (isEmpty(s))
{
printf("Stack Underflow !!!");
exit(1);
}
return s->data[s->top];
}
int main() {
struct stack stk;
int choice;
int value;
initstack(&stk);
while(1)
{
printf("1. PUSH\n");
printf("2. POP\n");
printf("3. STACKTOP\n");
printf("4. EXIT\n");
printf("Enter Your Choice:");
scanf("%d", &choice);
switch(choice)
{
case 1 :
printf("Enter Value:");
scanf("%d", &value);
push(&stk, value);
break;
case 2 :
printf("Popped Element Is %d \n", pop(&stk));
break;
case 3 :
printf("Topmost Element Is %d \n", stacktop(&stk));
break;
case 4:
return 0;
}
}
return 0;
}
Q.5) What is the difference between pop() operation and stacktop() / peek() operation?
pop() operation removes the topmost element from stack , hence stack size is decreased by one with every call to pop().
stacktop() operation does not remove topmost element from stack, hence stack size remains unchanged.
Want to read more?
Subscribe to questionbankos.com to keep reading this exclusive post.