More About Stacks: Stack Applications: Dan Nguyen CS 146, Spring 2004 Professor Sin-Min Lee
More About Stacks: Stack Applications: Dan Nguyen CS 146, Spring 2004 Professor Sin-Min Lee
Stack Applications
Dan Nguyen
CS 146, Spring 2004
Professor Sin-Min Lee
Quick Introduction
• Stacks are linear lists.
• All deletions and insertions occur at one
end of the stack known as the TOP.
• Data going into the stack first, leaves out
last.
• Stacks are also known as LIFO data
structures (Last-In, First-Out).
Basic Stack Operations
• push – Adds an item to the top of a stack.
The problem with this code is that it will print the binary
number backwards. (ex: 19 becomes 11001000 instead of 00010011. )
To remedy this problem, instead of printing the digit right away, we can
push it onto the stack. Then after the number is done being converted, we
pop the digit out of the stack and print it.
Stack Applications
• Postponement: Evaluating arithmetic expressions.
• Prefix: + a b
• Infix: a + b (what we use in grammar school)
• Postfix: a b +
a) A * B - ( C - D ) + E empty empty
b) * B - ( C + D ) + E empty A
c) B - ( C + D ) + E * A
d) - ( C + D ) + E * A B
e) - ( C + D ) + E empty A B *
f) ( C + D ) + E - A B *
g) C + D ) + E - ( A B *
h) + D ) + E - ( A B * C
i) D ) + E - ( + A B * C
j) ) + E - ( + A B * C D
k) + E - A B * C D +
l) + E empty A B * C D + -
m) E + A B * C D + -
n) + A B * C D + - E
o) empty A B * C D + - E +
Postfix Evaulation
Operand: push
Operator: pop 2 operands, do the math, pop result
back onto stack
1 2 3 + *