Stack
Stack
Adding & removing the elements possible at one end i.e, top end
Stack follows LIFO mechanism that means Last In First Out
Adding the into the stack we using push() operation
Removing the elements from the stack we using pop() operation
Stack operation:
The basic operations of stack we using
1. PUSH()
2. POP()
3. TRAVERSE()
Applications of Stack:
Converting infix to postfix expression
It is used in virtual machine like JVM
History of visited websites
Messages logs and all messages you get are arranged in stack
Call logs, E-mails, Google photos in Gallery, YouTube downloads, notifications
Step -1: a pointing variable is called top is used to keep track of the top element in the stack. When
initializing the stack, we set its value is ‘-1’. So that we can check if the stack is empty, that means
top==-1
Here top=-1
Stack[4]
Stack[3]
Stack[2]
Stack[1]
Stack[0]
Stack[4]
Stack[3]
Stack[2]
Stack[1]
10 Stack[0]
2. Adding an element into the stack previously top =0
Then top++ ===> top =1
Syntax: stack[top]=element;
Stack[1] =20;
Stack[4]
Stack[3]
Stack[2]
20 Stack[1]
10 Stack[0]
Stack[4]
Stack[3]
30 Stack[2]
20 Stack[1]
10 Stack[0]
4. Adding an element into the stack previously top =2
Then top++ ===> top =3
Syntax: stack[top]=element;
Stack[3] =40;
Stack[4]
40 Stack[3]
30 Stack[2]
20 Stack[1]
10 Stack[0]
5. Adding an element into the stack previously top = 3
Then top++ ===> top =4
Syntax: stack[top]=element;
Stack[4] =50;
50 Stack[4]
40 Stack[3]
30 Stack[2]
20 Stack[1]
10 Stack[0]
6. Adding an element into the stack previously top =4
Then top++ ===> top =5
Stack is full so insertion is not possible
50 Stack[4]
40 Stack[3]
30 Stack[2]
20 Stack[1]
10 Stack[0]
Step -3: POP()
Stack[4]
40 Stack[3]
30 Stack[2]
20 Stack[1]
10 Stack[0]
2. Deletion of an element from the stack previously top =3
Then top-- =====> top =2; stack [2]
Then deleted element is 40
Stack[4]
Stack[3]
30 Stack[2]
20 Stack[1]
10 Stack[0]
3. Deletion of an element from the stack previously top =2
Then top-- =====> top =1; stack [1]
Then deleted element is 30
Stack[4]
Stack[3]
Stack[2]
20 Stack[1]
10 Stack[0]
Stack[4]
Stack[3]
Stack[2]
Stack[1]
10 Stack[0]
Stack[4]
Stack[3]
Stack[2]
Stack[1]
Stack[0]
Stack[4]
Stack[3]
Stack[2]
Stack[1]
Stack[0]
For(top=4;top>=0;--top)
Printf(“%d\t”,stack[top]);
}
Program:
#define size 5
int stack[size];
int top = -1;
void push(int ele);
void pop();
void traverse();
void main() {
int choice,ele;
clrscr();
while(1)
{
printf("************ stack menu ************\n");
printf("\n 1. push \n 2. pop \n 3. traverse \n 4. exit \n");
printf("Choose one: ");
scanf("%d",&choice);
switch(choice)
{
case 1: printf("enter a value to insert");
scanf("%d",&ele);
push(ele);
break;
case 2: pop();
break;
case 3: traverse();
break;
case 4: exit(0);
break;
default: printf("\nInvalid choice (1-4)\n");
}
}
getch();
}