Documente Academic
Documente Profesional
Documente Cultură
Stacks
(Application, ADT Interface, Implementation)
• Stacks (§ 4.1)
• Sample Case Study (§ 4.5)
Stack ADT
C
B
A
invoked terminated
method method
main() {
Top of Java Stack:
job2: … … job1();
currently running method };
job1: …
job1() {
main: … … job2();
Java Stack };
4
fact(n)
Java Stack
What would happen if for every single value of n the recursive method would invoke itself,
i.e. there was no “terminating” value of n?
5
There are many ways to implement Stack, but all should have the same interface:
Possible Stack ADT Errors - there are 2 types of stack errors that
can occur:
pop
(1) underflow - trying to pop or peek
at an empty stack
• can occur regardless of the underlying
data structure employed
push
(2) overflow - trying to push onto an
already full stack
• can occur only if the underlying data
structure has a fixed capacity
7
Array of references!!!
Required private Object S[ ];
Instance Variables /* array used to implement the stack */
top=2 2
public static int top;
/* index of the top element of the stack, in the array */
1
Stack bottom is at S[0], and “top” represents the last position used.
9
Method Time
size O(1)
isEmpty O(1)
top O(1)
push O(1)
pop O(1)
Assume we have only the reference to the head of a Singly Linked List.
Where to place the top – at the head or the tail of the SLL??
(1) top = head ⇒ run time of insert and delete O(1)
(2) top = last element in SLL ⇒ run time of insert and delete O(n)
direction of
traversing
the SLL
head of SLL
13
public LinkedStack() {
top = null;
size=0; }
cont.
14
Method Time
size O(1)
isEmpty O(1)
top O(1)
push O(1)
pop O(1)
ordered access + +
insertions/removals
at a cursor
- +
frequent resizing - +
implementation
complexity / cost + -
A*[(B+C)/D+E] A*[(B+C/D+E]
Stack empty at the Stack not empty at
end of expression the end of expression
( ⇓ ( ( ( ⇓
brackets are brackets are
[ [ [ balanced !!! [ [ [ [ not balanced !!!
18
Computing Spans - given an array X, the span S[i] of X[i] is the max
number of consecutive elements X[j] immediately
≤X[i]
preceding X[i], such that X[j]≤
stock
price
1 3 2 2 week
19
“spans1” Algorithm
n-1 i-1
X 3 5 9 2 7 6 5 T(n) ≈ ∑ ∑ 1 = 1+ 2 + .. + (n − 1) = O(n 2 )
S 1 2 3 1 2 1 1
i=0 j=0
20
Q.2 Make a sketch of a program that reads a word and then writes it
backwards, using Stack ADT.
Q.3 Describe how you can define a new Stack ADT method that
returns the second item from the top of the stack, without
permanently changing the stack. (If you temporarily change
the stack, then you are required to change it back before the
method ends.)
Your description will be in terms of peek(), pop(), and push().