Stack
Stack
STACK
A data structure to store data in which the
elements are added and removed from one end
only: a Last In First Out (LIFO) data structure
3
• Pop – first increment stk_ptr
2 and then take data out
1
0
GROWING DOWNWRDS
Initial state: stk_ptr = MAX
• stk_ptr points to the last
9 12 element added to the stack
8 3
7 8
3
• Pop – first take data out and
2 then increment stk_ptr
1
0
GROWING UPWRDS
Initial state: stk_ptr = 0
7
• Push – first add data to the
6 stack then increment stk_ptr
5
4 6
• Pop – first decrement stk_ptr
3 4 and then take data out
2 5
1 2
0 7
GROWING UPWRDS
Initial state: stk_ptr = -1
7
• Push – first increment the
6
stk_ptr and then add data
5
4 6
• Pop – first take data out and
3 4 then decrement stk_ptr
2 5
1 2
0 7
STACKS – ARRAY IMPLEMENTATION
class Stack {
private:
int size; // maximum storage capacity
int stk_ptr; // stack pointer
int *stackArray; // array used to implement stack
public:
Stack(int s ); // constructor
~Stack() {delete [ ] stackArray; } // destructor
bool push (int); // add an element to the stack
bool pop(int &); // remove an element from stack
bool isFull(); // check if the stack is full
bool isEmpty(); // check if the stack is empty
};
Stack::Stack(int s) bool Stack::ifEmpty()
{ {
size = s; return (stk_ptr == 0);
stk_ptr = 0; }
stackArray = new int[size]; bool Stack::ifFull()
} {
return (stk_ptr == size);
}
Infix Postfix
a+b*c abc*+
a*b+c*d ab*cd*+
(a+b)*(c+d)/e-f ab+cd+*e/f-
a/b-c+d*e-a*c ab/c-de*+ac*-
a+b/c*(e+g)+h-f*i abc/eg+*+h+fi*-
ALGORITHM TO EVALUATE EXPRESSIONS
IN RPN
1. while (not end of expression) do
1. get next input symbol
2. if input symbol is an operand then
1. push it into the stack
3. else if it is an operator then
1. pop the operands from the stack
2. apply operator on operands
3. push the result back onto the stack
2. End while
3. the top of stack is answer.
POST EXPRESSION CALCULATOR
Expression: 6 3 + 2 * = 18 1. Push 6
2. Push 3
3. Symbol is + so
1. If symbol is operand then push it pop 2 times
in the stack
2. Else if symbol is operator then 4. Push result = 9
pop 2 operands and perform 5. Push 2
action & push the result in the
stack again 6. Symbol is * so
3. else if symbol is = then the pop 2 times
expression ends. Pop the result &
display
32 7. Push result = 18
8. Symbol is = so
6+3 = 9 pop & display
18 6 9
9*2 = 18
ALGORITHM TO EVALUATE EXPRESSIONS IN
RPN
(a+b)*(c+d) → ab+cd+*
Assuming a=2, b=6, c=3, d=-1