You are on page 1of 28

1

Lecture #5
• Stacks
2

Recap
• Advanced Linked Lists
– Tail Pointers
– Doubly-linked Lists
Stacks
Why should you care?

Stacks are used for:

Solving mazes
Undo in your word processor
Evaluating math expressions
Tracking where to return from C++
function calls

They’re so fundamental that a stack is


hard-wired into every CPU!

So pay attention!
4

The Stack: A Useful ADT


A stack is an ADT that holds a collection of items (like ints)
where the elements are always added to one end.

Just like a stack of plates, the last item pushed onto the
top of a stack is the first item to be removed.

Stack operations:
• put something on top of the stack (PUSH)
• remove the top item (POP)
• look at the top item, without removing it
• check to see if the stack is empty

We can have a stack of any type of variable we like:


ints, Squares, floats, strings, etc.
The Stack
5
Note: The stack is called
a Last-In-First-Out
data structure.
I can… Can you figure out why?
Push 5 on the stack.
last in first out
Push -3 on the stack.
Push 9 on the stack.
Pop the top of the stack. 4
9
Look at the stack’s top value. -3
Push 4 on the stack. 5
Pop the top of the stack
Pop the top of the stack
Look at the stack’s top value.
Pop the top of the stack

Note: You can only access the top item of the stack,
since the other items are covered.
6

Stacks
int main(void)
class Stack // stack of ints {
{ Stack is;
public:  
Stack(); // c’tor is.push(10);
is.push(20);
void push(int i);
int pop(); ...
bool is_empty(void); }
int peek_top();
private:
... Answer:
}; How about an array
and a counter variable
to track where the
top of the stack is?
Question:
What type of data structure can we
use to implement our stack?
Implementing a Stack
7

const int SIZE = 100;


class Stack
{
public:
Stack() { m_top = 0; } 
void push(int val) {
if (m_top >= SIZE) return; // overflow!
m_stack[m_top] = val;
m_top += 1;

int pop() {
if (m_top == 0) return -1; // underflow
m_top -= 1;
return m_stack[m_top];
...
private:
int m_stack[SIZE];
int m_top;
};
Stacks
8

int main(void)
const int SIZE = 100; {
class Stack Stack is;
{ Currently, our m_top points to the int a;
The
next second
open slot item
in the we
stack…
public: 1 10
>=>=100?
>= 100?
100?
push7 =will
10
5
m_stack[1]
m_stack[0]
m_stack[1]
Stack() { m_top be ==placed
0; }  10
7
5 in is.push(5);
But we
void push(int want
slot
val)#1to
{of return the top item
our stack. is.push(10);
already
if (m_top pushed
>= SIZE) on the//stack.
return; overflow a = is.pop();
m_stack[m_top] = val; cout << a;
m_top So
+= first
1; we must decrement our is.push(7);
} m_top
2 == variable…
0??
}
 
return
int pop() { m_stack[1] is
So we
if (m_top == return
0) return 10 -1; // underflow m_top 2
0
1
m_top -= 1;
return m_stack[m_top]; m_stack
} 0 5
...
1 7
10
2
private: ... …
int m_stack[SIZE];
10
7 99
int m_top; 5 a
}; 10
Stacks
9

Always Remember:
const int SIZE = 100; When we push, we:
class Stack
{ A. Store the new item in m_stack[m_top]
public: B. Post-increment our m_top variable
Stack() { m_top = 0; }  (post means we do the increment after storing)
void push(int val) {
if (m_top >= SIZE) return; // overflow
m_stack[m_top] = val;
m_top += 1;
}
 
int pop() {
if (m_top == 0) return -1; // underflow
m_top -= 1;
return m_stack[m_top]; Always Remember:
}
When we pop, we:
... A. Pre-decrement our m_top variable
private: B. Return the item in m_stack[m_top]
int m_stack[SIZE]; (pre means we do the
int m_top; decrement before returning)
};
Stacks
10

And as with cin and cout, you can


Here’s the syntax to define a stack:
remove the std:: prefix if you add a
Stacks are so popular that the C++ people
using actually
namespace std; wrote
std::stack<type> variableName;
one for you. It’s in the Standard Template Library (STL)!
command!
For example:
#include <iostream>
#include <stack> // required! stackOfStrings;
std::stack<string>
using namespace std; std::stack<double> stackOfDoubles;
int main()
{
stack<int> istack; // stack of ints
std::stack<int>
  So to get the top item’s value, before
istack.push(10); // addpopping
item to it, top
use the top() method!
istack.push(20);

cout << istack.top(); // get top value


istack.pop(); // kill top value
Note: The STL pop() command
simply throws away the top item
if (istack.empty() == false)
cout << istack.size(); from the stack…
} but it doesn’t return it.
11

Stack Challenge
Show the resulting stack after the following program runs:

#include <iostream>
#include <stack>
using namespace std;
 
int main()
{
stack<int> istack; // stack of ints

istack.push(6);
for (int i=0;i<2;i++)

int n = istack.top();
istack.pop();
istack.push(i);
istack.push(n*2);
}
}
12

Stack Challenge
Show the resulting stack after the following program runs:

#include <iostream>
#include <stack>
using namespace std;
 
int main()
{ i 0
1
stack<int> istack; // stack of ints
n
istack.push(6);
for (int i=0;i<2;i++) 24
{  12
1
int n = istack.top();
6
0
istack.pop();
istack.push(i);
istack.push(n*2);
}
}
13

Common Uses for Stacks


Stacks are one of the most USEFUL data structures
in Computer Science.

They can be used for:


• Storing undo items for your word processor
The last item you typed is the first to be undone!
• Evaluating mathematical expressions
5 + 6 * 3  23
• Converting from infix expressions to postfix
expressions
A+BAB+
• Solving mazes

In fact – they’re so fundamental to CS that they’re


built into EVERY SINGLE CPU in existence!
14

A Stack… in your CPU!


Did you know that every CPU has a built-in stack used
to hold local variables and function parameters?

void bar(int b)
{ When you pass a value to a function,
cout << b << endl; the CPU pushes that value onto a stack
} in the computers memory.
 
void foo(int a)
{ … when your function returns, the values
cout << a << endl; are popped off the stack and go away.
10
bar(a*2);
} Output: b
  10
int main(void) Every a a local
5 time you declare 5 variable,
{ program pushesxit on the PC’s stack
your10
int x = 5; automatically!
5
foo( 5
x );
}
Undo!
15

When the user hits the


So undo
how does the UNDO
button…
feature of your favorite
so cool
Carey is not
so
word processor
The word processorwork?
pops the top item off
the stackaand
It uses removes
stack, of course!
it from the document!
Every time you type a new
word, it’s added to the stack!

Every time you cut-and-paste “so” “not”


“so” “not”
an image into way,
In this your the
doc,word
it’s img5.jpg
“cool”
added tocan
processor thetrack
stack!
the last X “so”
things that you did and
And even when you delete “is”
properly undo them!
text or pictures, this is “Carey”
tracked on a stack! undo stack
16

Postfix Expression Evaluation


Most people are used to infix notation, where the
operator is in-between the two operands, e.g.: A + B

As we’ll
Postfix notation is another waysee, postfix
to write expressions
algebraic have–
expressions
here the operator follows
no the
suchoperands: AB+
ambiguity!

Infix Postfix
Here are some infix 15 + 6 15 6 +
If you’ve ever
expressions andused an9 HP
– 4 Is that9 (5+10)
4 - *3
calculator, you’ve used
their postfix
(15 + 6) * 5 15or
6 + 5 *
equivalents:
postfix notation!
7 * 6 + 5 5 +7(10
6 ** 53)+
To3 understand
+ (4 * 5) infix
3 4 5expressions,
* + the
computer has to be equipped with
Postfix expressions are easier forprecedence
a computer torules!
compute than
infix expressions, because they’re unambiguous.

Ambiguous infix expression example: 5 + 10 * 3


17

Postfix Evaluation Algorithm


Inputs: postfix expression string
Output: number representing answer 7 6 * 5 +
Private data: a stack
1. Start with the left-most token. v1v1==42
7 v2 v2==65
2. If the token is a number: temp =
temp =67*6 = =42
542+5 47
a. Push it onto the stack 42
47
7
3. Else if the token is an operator:
a.… //
Popwe’ll
thesee
topthis
valueininto a variable called v2, and
a bit!
the second-to-top value into v1.
b. Apply operator to v1 and v2 (e.g., v1 / v2)
c. Push the result of the operation on the stack
4. If there are more tokens, advance to the next
token and go back to step #2
5. After all tokens have been processed, the top #
on the stack is the answer!
18

Class Challenge
Given the following postfix expression: 6 8 2 / 3 * -
Show the contents of the stack *after* the 3 has been
processed by our postfix evaluation algorithm.
Reminder:
1. Start with the left-most token.
2. If the token is a number:
a. Push it onto the stack
3. If the token is an operator:
a. Pop the top value into a variable called v2, and the
second-to-top value into v1.
b. Apply operator to the two #s (e.g., v1 / v2)
c. Push the result of the operation on the stack
4. If there are more tokens, advance to the next token and go
back to step #2
5. After all tokens have been processed, the top # on the stack
is the answer!
19

Infix to Postfix Conversion


Since people are more
Stacks can also be used to convert infix expressions to
used to infix notation…
postfix expressions:
You can let the user
For example,
type in an infix
expression…
From: (3 + 5) * (4 + 3 / 2) – 5
To: 3 5 + 4 3 2 / + * 5 –
And then convert it into
a postfix expression.
Or
Finally, you can use the
From: 3 + 6 * 7 * 8 – 3
postfix evaluation alg
To: 3 6 7 * 8 * + 3 - (that we just learned)
to compute the value of
the expression.
20

Infix to Postfix Conversion


Inputs: Infix string
Output: postfix string (initially empty)
Private data: a stack
1. Begin at left-most Infix token.
2. If it’s a #, append it to end of postfix string followed by a space
3. If its a “(“, push it onto the stack.
4. If its an operator and the stack is empty:
a. Push the operator on the stack.
5. If its an operator and the stack is NOT empty:
a. Pop all operators with greater or equal precedence off the

stack and append them on the postfix string.


b. Stop when you reach an operator with lower precedence or a (.
c. Push the new operator on the stack.
6. If you encounter a “)”, pop operators off the stack and append
them onto the postfix string until you pop a matching “(“.
7. Advance to next token and GOTO #2
8. When all infix tokens are gone, pop each operator and append it }
21

Solving a Maze with a Stack!


We can also use a stack to determine if a maze is
solvable:

0 1 2 3 4 5 6 7
Start 0
(1,1) 1
2
3
4 Finish
5 (6,6)
6 X
7
22

Solving a Maze with a Stack!


Inputs: 10x10 Maze in a 2D array,
Starting point (sx,sy)
Ending point (ex,ey)
Output: TRUE if the maze can be solved, FALSE otherwise
Private data: a stack of points

class Point class Stack


{ {
public: public:
Point(int x, int y); Stack(); // c’tor
int getx() const; void push(Point &p);
int gety() const; Point pop();
private: ...
int m_x, m_y; private:
}; ...
};
Solving a Maze with a Stack!
23

sx,sy = 1,1
0 1 2 3 4 5 67
1. PUSH starting point onto the stack.
2. Mark the starting point as “discovered.”
0 ?
1 ? ##?
3. If the stack is empty, there is
NO SOLUTION and we’re done!
2 ?
#
3
4. POP the top point off of the stack. 4
5. If we’re at the endpoint, DONE! Otherwise… 5
6. If slot to the WEST is open & is undiscovered 6 x
Mark (curx-1,cury) as “discovered” 7
PUSH (curx-1,cury) on stack.
7. If slot to the EAST is open & is undiscovered 1,1 == 6,6?
Mark (curx+1,cury) as “discovered” Not yet!
PUSH (curx+1,cury) on stack.
8. If slot to the NORTH is open & is undiscovered
Mark (curx,cury-1) as “discovered”
PUSH (curx,cury-1) on stack.
9. If slot to the SOUTH is open & is undiscovered
Mark (curx,cury+1) as “discovered”
PUSH (curx,cury+1) on stack.
1,2
10. GOTO step #3 2
1,1
cur = 1,1
Solving a Maze with a Stack!
24

0 1 2 3 4 5 67
1. PUSH starting point onto the stack. 0
2. Mark the starting point as “discovered.” 1 ?#
#
3. If the stack is empty, there is 2 ? #?
NO SOLUTION and we’re done! 3 ?
#
4. POP the top point off of the stack. 4
5. If we’re at the endpoint, DONE! Otherwise… 5
6. If slot to the WEST is open & is undiscovered 6 x
Mark (curx-1,cury) as “discovered” 7
PUSH (curx-1,cury) on stack.
7. If slot to the EAST is open & is undiscovered 1,2 == 6,6?
Mark (curx+1,cury) as “discovered” Not yet!
PUSH (curx+1,cury) on stack.
8. If slot to the NORTH is open & is undiscovered
Mark (curx,cury-1) as “discovered”
PUSH (curx,cury-1) on stack.
9. If slot to the SOUTH is open & is undiscovered
Mark (curx,cury+1) as “discovered”
PUSH (curx,cury+1) on stack.
1,3
2
10. GOTO step #3 2,1
cur = 1,2
Solving a Maze with a Stack!
25

0 1 2 3 4 5 67
1. PUSH starting point onto the stack. 0
2. Mark the starting point as “discovered.” 1 ##
3. If the stack is empty, there is 2 ?
#
NO SOLUTION and we’re done! 3 ? #?
4. POP the top point off of the stack. 4 ?
5. If we’re at the endpoint, DONE! Otherwise… 5
6. If slot to the WEST is open & is undiscovered 6 x
Mark (curx-1,cury) as “discovered” 7
PUSH (curx-1,cury) on stack.
7. If slot to the EAST is open & is undiscovered 1,3 == 6,6?
Mark (curx+1,cury) as “discovered” Not yet!
PUSH (curx+1,cury) on stack.
8. If slot to the NORTH is open & is undiscovered
Mark (curx,cury-1) as “discovered”
PUSH (curx,cury-1) on stack.
9. If slot to the SOUTH is open & is undiscovered
Mark (curx,cury+1) as “discovered”
PUSH (curx,cury+1) on stack.
1,3
10. GOTO step #3 2,1
cur = 1,3
Solving a Maze with a Stack!
26

0 1 2 3 4 5 67
1. PUSH starting point onto the stack.
2. Mark the starting point as “discovered.”
0 ?
1 ?##
# ?
3. If the stack is empty, there is 2 #?
NO SOLUTION and we’re done! 3 #
4. POP the top point off of the stack. 4
5. If we’re at the endpoint, DONE! Otherwise… 5
6. If slot to the WEST is open & is undiscovered 6 x
Mark (curx-1,cury) as “discovered” 7
PUSH (curx-1,cury) on stack.
7. If slot to the EAST is open & is undiscovered 2,1 == 6,6?
Mark (curx+1,cury) as “discovered” Not yet!
PUSH (curx+1,cury) on stack.
8. If slot to the NORTH is open & is undiscovered
Mark (curx,cury-1) as “discovered”
PUSH (curx,cury-1) on stack.
9. If slot to the SOUTH is open & is undiscovered
Mark (curx,cury+1) as “discovered”
PUSH (curx,cury+1) on stack.
10. GOTO step #3 3
2,1
cur = 2,1
Solving a Maze with a Stack!
27

0 1 2 3 4 5 67
1. PUSH starting point onto the stack.
2. Mark the starting point as “discovered.”
0 ?
1 ##? ## ?
3. If the stack is empty, there is 2 # # ?
NO SOLUTION and we’re done! 3 #
or o ur
4. POP the top point off of the stack. 4 ze, !
5. If we’re at the endpoint, DONE! Otherwise… the 5ma olu ti on
n t o n o s
6. If slot to the WEST is open & is undiscovered
so l u tio he re6 is x
d
Mark (curx-1,cury) asn“discovered” the h at t .”
f i
’ll on stack. ti n g t 7
ea rc h
y ,
PUSH (curx-1,cury)w e d i ca
in& is undiscovered r st s
n tu a ll EAST is o u t, p t h -fi3,1 == 6,6?
e
7. If vslot
E Mark to the
m p ty open
a “ de
w i ll e
(curx+1,cury) as “discovered” alle d Not yet!
c k
staPUSH (curx+1,cury) onrstack. mi s c
ith
oopen & is undiscovered
g a l g
8. If slot to the NORTH
a r c h in is
is se(curx,cury-1) as “discovered”
Mark
ThPUSH (curx,cury-1) on stack.
9. If slot to the SOUTH is open & is undiscovered
Mark (curx,cury+1) as “discovered”
PUSH (curx,cury+1) on stack.
3,2
10. GOTO step #3 3
4,1
cur = 3,1
28

Next Lecture
• Queues

You might also like