STACKS
Made By PUSHKAR DUA
WHAT IS A STACK?
A pile of objects, typically one that is neatly arranged. Stack Follows LIFO Last IN First OUT ie. Last element to be PUSHED (inserted) should be the first one to POP (remove) out of stack.
Made By PUSHKAR DUA
REPRESENTATION OF STACK
A stack is printed FROM TOPMOST element (last pushed) TO FIRST element. LAST element pushed on stack is always printed first and keeps on printing till 1st element. If elements inserted are 53,24,34,21,78 respectively , stack will be represented as
Made By PUSHKAR DUA
HOW TO KEEP TRACK OF ELEMENTS
To keep a tack on last element in a stack, we use a variable named TOP. When the stack is empty, TOP = -1 When stack is full, TOP = size-1; The no of elements in stack can be calculated as TOP+1.
Made By PUSHKAR DUA
HOW TO PUSH ELEMENTS TO STACK
To insert an element in stack : Check top !=size-1 Top=Top+1 Scanf ARR[TOP]
Made By PUSHKAR DUA
HOW TO POP AN ELEMENT FROM STACK
Element is always deleted from TOP, to delete an element from stack, Check TOP !=-1 TOP=TOP-1
Made By PUSHKAR DUA
TO DISPLAY A STACK
To display elements of stack, Check top=-1 For(I=size-1;i>=0;i++) Printf ARR[i]
Made By PUSHKAR DUA
MENU DRIVEN
#include <stdio.h> #include<process.h> void main() { int arr[20], choice,top=-1, i ; while(1) { printf("\n\n1. Push"); printf("\n2. Pop"); printf("\n3. Display"); printf("\n4. EXit"); printf("\nEnter Your Choice :"); scanf("%d",&choice); switch(choice) { case 1: if(top==19) printf("stack overflow");
case 3:
if(top==-1) printf("Stack UNDERFLOW"); else { for(i=top;i>=0;i--) printf("\n %d",arr[i]); break; } case 4: exit(0); default: printf("Wrong Choice"); }
else { top++; printf("\nEnter Value :"); scanf("%d",&arr[top]); } break;
case 2: if(top==-1) printf("Stack UNDERFLOW"); else top--; break;
}
Made By PUSHKAR DUA 8