Stacks and Applications: 05/11/11 Center For Development of Advanced Computing 1
Stacks and Applications: 05/11/11 Center For Development of Advanced Computing 1
• Advantages
– They are simple, easy to understand
– Each operation is O(1)
• Operations
– Push: placing an element in the stack
– Pop : removing an element in the stack
– Peep: check the top most element
– IsEmpty
– Is Full
05/11/11 Center for Development of Advanced Computing 4
Example of a stack
• Consider the elements Initially
{1,2,3,4}, stack ‘s’ and -1 0 1 2 3 4 5
tos at -1 tos
• Push Push 1 1
– Increment tos and place -1 0 1 2 3 4 5
the element
tos
• Pop Pop
Push 4
2
3 1 2 3 4
– Take the element and -1 0 1 2 3 4 5
decrement the tos
Int main()
{
int fact(int) ;
int fact_val = 0;
fact_val = fact(4) ;
return 0 ;
}
05/11/11 Center for Development of Advanced Computing 10
App 2: Balancing Symbols
• When analyzing arithmetic expressions, it is
important to determine whether an
expression is balanced with respect to
parentheses
– (a+b*(c/(d-e)))+(d/e)
• Problem is further complicated if braces or
brackets are used in conjunction with
parenthesis
• Solution is to use stacks!
05/11/11 Center for Development of Advanced Computing 11
Balancing Symbols
• start with an empty stack of characters
• traverse the expression from left to right
– if next character is a left delimiter, push onto the
stack
– if next character is a right delimiter, must match
the top of the stack