Professional Documents
Culture Documents
17/02/2009 15:49
Operations:
P USH(o) – insert object o at the top
P OP() – remove and return the top element (error if empty)
Stack semantics is LIFO = last in first out
An Array-based Implementation
An n-element array S and an integer index t that points to the top of the stack.
t
a b c
0 1 2 3 4 5 6 7 n−3 n−2 n−1
P USH(o)
P OP()
t
a b c o
0 1 2 3 4 5 6 7 n−3 n−2 n−1
1
2 Algorithms and Data Structures
P USH(o) P OP()
1 if t = n − 1 1 if t = −1
2 then error 2 then error
3 t←t+1 3 e ← S[t]
4 S[t] ← o 4 S[t] ← N ULL
5 t←t−1
6 return e
F (x : int) : int
1 y ← 2x
2 if 2x < 10
3 then return F(y)
4 else return y − 1
y x y x y x y x
return 15;
··· 16 8 8 4 4 2 2 1
There is a lot more on the actual stack. Here is a more detailed view:
return address
argument m
temporaries
argument n
argument 1
argument 2
argument 1
argument 2
variables
registers
saved
local
···
···
next
current frame previous frame
frame
Algorithms and Data Structures 3
In short: the same constant space for all calls of a specific function, only de-
pends on the parameters, local variables and the return type.
Remember: Function calls (including recursion) cost time and space!
Operations:
E NQUEUE(o) – insert object o at the rear
D EQUEUE() – remove and return the object at the front (error if empty)
Queue semantics is FIFO = first in first out
An Array-based Implementation
f r
a b c ···
0 1 2 3 4 5 6 7 n−3 n−2 n−1
E NQUEUE(o)
f r
a b c o ···
0 1 2 3 4 5 6 7 n−3 n−2 n−1
D EQUEUE()
f r
b c o ···
0 1 2 3 4 5 6 7 n−3 n−2 n−1
D EQUEUE() E NQUEUE(o)
1 if I S E MPTY() 1 if S IZE() = N − 1
2 then error 2 then error
3 temp ← Q[f ] 3 Q[r] ← o
4 Q[f ] ← null 4 r ← (r + 1) mod N
5 f ← (f + 1) mod N 5
6 return temp 6
The size of the queue is computed as (N − f + r). To avoid amibguity between
the empty and full queue (both happen when f = r) we only allow the queue
to hold N − 1 elements (line 1) in E NQUEUE.