Lecture 4 - Stack
Lecture 4 - Stack
Stack of Books
2
What is a Stack?
› A stack is a linear data structure of ordered items such
that items can be inserted and removed only at one
end.
3
What can we do with a stack?
› push - place an item on the stack
› peek - Look at the item on top of the stack, but
do not remove it
› pop - Look at the item on top of the stack and
remove it
4
A stack is a LIFO (Last-In/First-Out) data
structure
A stack is sometimes also called a pushdown
store.
What are some applications of stacks?
› Program execution
› Parsing
› Evaluating postfix expressions
5
2
top
8
top 8
1 1 1
top Push(8)
7 7 Push(2) 7
2 2 2
pop(
)
8
1
top
top 1
top 7 7 pop()
2 pop() 2
7
2
6
Problem:
› What happens if we try to pop an item off the stack
when the stack is empty?
This is called a stack underflow. The pop method needs
some way of telling us that this has happened. In java
we use the java.util.EmptyStackException
7
There are two ways we can implement a stack:
› Using an array
› Using a linked list
8
Implementing a stack using an array is fairly
easy.
› The bottom of the stack is at data[0]
› The top of the stack is at data[numItems-1]
› push onto the stack at data[numItems]
› pop off of the stack at data[numItems-1]
9
Implementing a stack using a linked list isn’t that
bad either…
› Store the items in the stack in a linked list
› The top of the stack is the head node, the bottom of
the stack is the end of the list
› push by adding to the front of the list
› pop by removing from the front of the list
10
We can use a stack to reverse the letters in a
word.
How?
11
Read each letter in the word and push it onto the
stack
When you reach the end of the word, pop the
letters off the stack and print them out.
12
Some direct applications:
› Page-visited history in a Web browser
› Undo sequence in a text editor
› Chain of method calls in the Java Virtual Machine
› Evaluating postfix expressions
13
(5+9)*2+6*5
An ordinary arithmetical expression like the above is called
infix-expression (i.e. binary operators appear between their
operands)
14
Expressions can also be represented using postfix notation (i.e. each
operator comes after its two operands).
Infix Postfix
16 / 2 16 2 /
(2 + 14)* 5 2 14 + 5 *
2 + 14 * 5 2 14 5 * +
(6 – 2) * (5 + 4) 6 2 - 5 4 +*
The following algorithm uses a stack to evaluate a
postfix expression.
Start with an empty stack
for (each item in the expression) {
if (the item is a number)
Push the number onto the stack
else if (the item is an operator){
Pop two operands from the stack
Apply the operator to the operands
Push the result onto the stack
}
}
Pop the only one number from the stack – that’s the result of the evaluation
Example: Consider the postfix expression, 2 10 + 9 6 - /, which is (2
+ 10) / (9 - 6) in infix, the result of which is 12 / 3 = 4.
The following is a trace of the postfix evaluation algorithm for the above.
Java Libraries:
› Use the Java Collections Framework:
java.util.Stack (legacy)
20