Ch3 - Stack Using Array (1) (2)
Ch3 - Stack Using Array (1) (2)
Data Structures
A stack is an ordered list in which all insertions and deletions of entries are made at one
end, called the top of the stack.
When we insert an item, we say that we push it onto the stack.
The last item pushed onto a stack is the first item popped.
A stack is a dynamic object, it expands and shrinks with each push and pop.
top top
A M
Q Q top R top R
Q top top
Push Push(A Pop Pop Push Push
(Q) ) () () (R) (M)
empt
y
peak(): Returns the top element on the stack but does not remove it from the
stack.
10
Faculty of Information Technology - Computer Science Department
Methods Implementation
11
Faculty of Information Technology - Computer Science Department
Main Class
12
Faculty of Information Technology - Computer Science Department
Main Class - Outputs
1. unary +, - (positive,
negative)
2. ×, /, %
3. +, - .
5. otherwise, pop from the stack, and add on the postfix queue all operators whose
priority is higher or equal to the priority of the token and then push the token.
Faculty of Information Technology - Computer Science Department
4. Repeat steps 2 and 3 until the token is the end token. 16
Conversion of Infix Expressions to Postfix Expressions
17
Faculty of Information Technology - Computer Science Department
Evaluate the Postfix Expression
Step 1: Repeatedly get token from postfix expression
Step 2: If the token is an operand: Push the value to the stack
Step 3: If it is an operator: Pop 2 values, evaluate, and push the
result.
18
Faculty of Information Technology - Computer Science Department