A stack can be implemented as a list, all operations are performed
at the head of the list.
An array can be used as well, the first element at position 0, the
last at position n. Insert at position n+1, pop to position n-1
Some Applications:
Balanced Expressions:
Given an expression with [] () <> or any set of
expressions <a href=...> </a>, determine if the
expressions are balanced, or does every set match, and have
an opening and closing expression.
([<>]){} is fine
{[}] is not.
Algorithm
Balanced Expression:
Create a new stack S
while more text
get next symbol t
If t ∈{opening symbol}
S.push(t)
If t ∈{closing symbols}
q = S.Top();
if (q != t)
return error
if !S.Empty()
return error
return no-error
Argue that it works.
Argue performance.
Evaluating a postfix expression
A postfix expression is an expression where operands are given before the operators.
3 5 + is the same as the infix expression 3+5
3 4 + 5 * is (3+4)5
3 4 5 + * is 3(4+5)
The nice thing about postfix is that any expression can be written without parentheses.
This is also called reverse polish notation (or rpn)
Give an algorithm to evaluate an RPN expression.
Function Calls.
Each time a routine is called the activation record is pushed onto the run time stack.