Data structure & Algo
Data structure & Algo
TOPIC- STACKS
STACKS
➢ Definition:-
▪ A stack is an ordered list in which insertion and deletion are done at one end, called TOP.
▪ The last element inserted in a stack is the first one to be deleted. Hence, it is called
the Last In First Out (LIFO) or the First In Last Out (FILO) list.
▪ A pile of plates in a cafeteria is a good real life example of a stack. The plates are added to the top one
after another. And when required, it is taken from the top of the stack. There are other examples like
stack of books etc.
❑Operations on stack :
There are two kinds of operations that can be performed on a stack. They
are-
• PUSH
• POP
➢ PUSH : This function adds elements/ items into the stacks. Whenever
we add an element into the stack the pointer "TOP" gets incremented as -
TOP = TOP + 1 Or, TOP++
This is used to show the position of the element in the stack. When there is
no more space left in the stack, it indicates "STACK OVERFLOW".
➢ POP : This function deletes elements/ items from the stacks. Whenever
we remove an element from the stack the pointer "TOP" gets
decremented as -
TOP = TOP – 1 Or, TOP- -
This is used to show the position of the element in stack. When there is no
more element in the stack it indicates "STACK UNDERFLOW / EMPTY". Push & Pop operation
ALGORITHM FOR PUSH OPERATION
Step 3 : Set stack [ top] = item Step 2 : else item = stack [ top]
1 2 3 4
• A Stack can be used for evaluating expressions consisting of operands and operators.
• Stacks can be used for Backtracking, i.e., to check parenthesis matching in an expression.
❑ Expression Representation:
Step 5: If it is a closing parenthesis, delete the operator from stack and display them until an opening
parenthesis is encountered. Delete and discard the opening parenthesis.
• When the variable is not used outside the function in any program, the Stack can be used.
❑Disadvantages of Stack :
• It is difficult in Stack to create many objects as it increases the risk of the Stack overflow.