The interaction between
algorithm and
data structure
- Recall:
- Computer program =
algorithm +
data structure(s)
|
- Algorithms can
produce and
consume
information in
different ways:
- Some
algorithms
consume the
data in the
same order as
how the data was
produced
Production order: A B C D
Consumption order: A B C D
|
- Some
algorithms
consume the
data in the
reverse order as
was
produced:
Production order: A B C D
Consumption order: D C B A
|
- Etc, etc
|
|
Intro to the
stack
data structure
Analogy for the
stack data structure
- A stack
data structure is
like a stack of
books:
|
Analogy for the
stack data structure
- The push operation
will "insert"/add
an item on
top of the
stack:
|
Analogy for the
stack data structure
Some
computer algorithms/processes
with a
natural LIFO
behavior
-
Method invocation
/return:
- If the
order of
method invocation is:
M1() --> M2() --> M3() --> M4()
|
- Then the
order in which
the methods
return from
their invocation is
the reverse order:
M4() --> M3() --> M2() --> M1()
|
|
- In CS 255, you will
learn more
about the
System Stack
maintained
by the
run time system that
is used to store the
parameter variables and
the local variables
of the method invocations
|
DEMO:
09-stack/10-call-stack/Demo.java
Some
computer algorithms/processes
with a
natural LIFO
behavior
- The
undo algorithm
in a text editor:
- If the
order of
changes you made to
a text file is:
M1() --> M2() --> M3() --> M4()
|
- Then the
order in which
the changes are
undone will
occur in
the reverse order:
M4() --> M3() --> M2() --> M1()
|
|
- This means that the
text editor will
use a
stack to
store the
history of
edit changes to
implement its
undo algorithm
|
❮
❯