Stacks Java
Stacks Java
What is a stack?
1
3 3
5 5 5
Push 3 Push 1
Push 5
Get 1 Get 3
7
3 5
5 5
Pop Pop Push 7
System Stack
◼ process of subroutine calls
O.S proc. MAIN proc. A1 proc. A2 proc. A3
end
q r s t q r s t
Top/ CURRENT-ADDR
Function Calls
When a subroutine calls another subroutine
(including itself) it must first store its register
contents.
So, it pushes the register contents into a stack.
The new function uses the registers.
When the program returns to the old function, pop
the stack.
Real life
◼ Stack of trays in cafeteria
◼ Piles of books in library
Computer Science
◼ Program Execution Stack
◼ Evaluating Expressions and Syntax Parsing
◼ Tower of Hanoi
◼ Undo operations
Implementation of Stack by
Array
◼ Implementation of stack ADT
◼ use an one-dim array stack[MaxSize]
◼ bottom element is stored in stack[0]
◼ top points to the top element
◼ initially, top=-1 for an empty stack
an-1
◼ data member declarations in class
class Stack
{ a2
private int items[];
private int top; a1
private int MaxSize; a0
public:
......
a0 a1 a2 an-1
Array index
0 1 2 3 n-1
Implementation of Stack by
Array (cont.)
◼ constructor definition
public Stack(int size)
{
items = new int[size];
top = -1;
MaxSize = max;
}
}
Implementation of Stack by
Array (cont.)
◼ Pop operation
public double pop() // take item from top of stack
{
if (IsEmpty())
{
System.out.println("Stack underflow");
System.exit(-1);
}
else
return items[top--];
}
..\..\Sample\SDemo.java
Example
Consider a mathematical expression that includes several sets of nested
parenthesis.
7 – ((x * (( x + y) / (j - 3)) + Y) / (4 – 2))
In expression we want to check
1.There are an equal number of right and left parenthesis.
2. Every right parenthesis is preceded by a matching left parenthesis.
Expressions like ((A+B) or A+B( violates condition 1 and expressions like )A
+ B(-C violate condition 2.
Nested Depth: is the number of scopes that have been opened and not
yet closed.
Parenthesis count: no of left parenthesis – no of right parenthesis.
Example (Cont’d)
Expression id valid if following conditions are met.
1. Parenthesis count at end should be zero.
2. Parenthesis count at each point in expression should be non negative.
7 – ( ( x * ( ( x + y ) / ( j - 3 ) ) + Y ) / ( 4 – 2.5 ) )
00122234444334444322 211222 210
( ( A + B ) and (A + B] is illegal
1 22221
Algorithm for Example
valid = true
s = empty stack;
while (we have not read the entire string) {
read the next symbol (symb) in the string;
if (symb == ‘(’ || symb == ‘{’ || symb == ‘[’ )
s.push(symb);
if (symb == ‘)’ || symb == ‘}’ || symb == ‘]’ )
if (empty(s))
valid = false;
else{
i = s.pop();
if (i is not the matching opener of symb)
valid = false }
}// end of while
if (!s.empty()) valid = false;
if (valid)
cout << “String is valid”;
else cout << “String is not valid”;
Parenthesis Stack
Consider expression
[x + {y – (a + b)}]
(
{ { {
[ [ [ [
[ x+{y-(a+b)} [ x+{y-(a+b)}]
Polish Notations
Expression can be written in prefix, postfix or infix
notations
◼ + A B prefix operator precedes operands
◼ A B + postfix operator precedes operands
◼ A + B infix
◼ Unlike Infix notation no parenthesis are
required to enforce precedence.
◼ Expressions are evaluated from left to
right.
Converting to Prefix, Postfix Notation
Precedence rules are used to convert expression
1) Exponentiation, 2. Multiplication/ Division 3. Addition/Subtraction
Converting to Prefix Notation
◼ (A+B)*C = [+AB]*C = *+ABC
◼ A+(B*C) = A+[BC*]=ABC*+
Exercises
◼ A$B*C-D+E/F/(G+H)
◼ ((A+B)*C-(D-E))$(F+G)
◼ A-B/(C*D$E)
◼ (A+B$D)/(E-F)+G
◼ A*(B+D)/E-f*(G+H/K)
Example: postfix expressions
(cont.)
Postfix expressions: using
stacks (cont.)
Postfix expressions: Algorithm
using stacks (cont.)
opndstk = the empty stack;
while (not end of input){
symb = next input character;
if (symb is an operand)
opndstk.push(symb);
else{
opnd2 = opndstk.pop();
opnd1 = opndstk.pop();
value = result of applying symb to opnd1 and opnd2;
opndstk.push(value) }
EXERCISE
623+-382/+*2$3+
symb op1 op2 value opndstk
6 6
2 62
3 623
+ 2 3 5 65
- 6 5 1 1
3 6 5 1 13
8 6 5 1 138
2 6 5 1 1382
/ 8 2 4 134
+ 3 4 7 17
* 1 7 7 7
2 1 7 7 72
$ 7 2 49 49
3 7 2 49 49 3
+ 49 3 52 52
Algorithm to Convert Infix Exp
to Postfix Expression
1. opstk = the empty stack;
2. while (not end of input){
3. symb = next input character;
4. if (symb is an operand)
add symb to the postfix string
5. else{
6. while (!opstk.empty () && prcd(opstk.Top(), symb)){
7. topsymb = opstk.pop();
8. add topsymb to the postfix string;
} /* end while*/
9. opstk.push(symb);
} /* end else*/
} /* end while*/
10. while (!opstk.empty()){
11. Topsymb = opstk.pop();
12. add topsymb to the postfix string;
} /* end while*/
EXERCISE
A+B*C
symb Postfix string opstk
A A
+ A +
B AB +
* AB +*
C ABC +*
ABC*+
EXERCISE
A*B+C
symb Postfix string opstk
A A
* A *
B AB *
+ AB* +
C AB*C +
AB*C+
Algorithm to Convert Infix Exp
to Postfix Expression
9. if (opstk.empty () || symb != ‘)’)
opstk .push(symb);
else
topsymb = opstk.pop();