What is Stack?
A stack is a linier list in which insertion and deletion operations are performed at only one end of the list. Thus you are able to insert as well as delete the element from only one end of the stack.
Since insertion and deletion operations are performed at same end, the element which is inserted Last is first to delete. So Stack is also known as Last In First Out (LIFO).
Consider a stack of plates at dinner counter. The person who comes for dinner takes off the plate which is at top of the stack. After washing the plates the waiter places the washed plates on the top of the stack. So the plate that is placed last is first take by person.
Operations Performed on Stack
There are two main operations that can be performed on stack.
The process of inserting an element into stack is known as PUSH operation.
In order to insert an element into stack first we have to check weather free space is available in the stack or not.
If stack is full then we can not insert an element into stack. If value of TOP variable is greater then or equal to SIZE – 1 then Stack is full. This condition is known as “Overflow”.
If stack is not overflow then we can insert an element into stack. First we have to increment the value of variable TOP by one and then insert an element into stack.
Step 1: If TOP >= SIZE – 1 then
Write “Stack is Overflow”
Step 2: TOP = TOP + 1
Step 3: STACK [TOP] = X
The process of deleting an element from stack is known as POP operation.
In order to delete an element from stack first we have to check weather stack is empty or not. If stack is empty then we can not delete an element from stack. This condition is known as “Underflow”.
If value of TOP variable is -1 then stack is empty. So we can not delete an element from stack.
If stack is not underflow then we can delete topmost element from stack. After deleting topmost element from stack, we have to decrement the value of TOP by one, so that it can point to the next topmost element in the stack.
Step 1: If TOP = -1 then
Write “Stack is Underflow”
Step 2: Return STACK [TOP]
Step 3: TOP = TOP - 1