Академический Документы
Профессиональный Документы
Культура Документы
$'
&
'
public stack () f
maxSize = DefaultMaxSize;
store = new Object [maxSize];
%&
.
.
.
%
$
class stack f
private int maxSize, top = -1;
public static final int DefaultMaxSize = 100;
private Object [] store;
&
%&
$'
$'
'
ray
doh
top
%&
$'
%
$
class Node f
// Use package-level visibility.
Object value;
Node next;
public Node (Object value, Node next) f
this.next = next;
this.value = value;
me
A Dynamic Approach to
Resource Allocation
&
'
g
return returnVal;
public LinkedStack () f
numElements = 0;
first = null;
&
%&
g
$'
'
public ArrayStack () f
maxSize = DefaultMaxSize;
store = new Object [maxSize];
g
public ArrayStack (int desiredMaxSize) f
maxSize = desiredMaxSize;
store = new Object [maxSize];
g
public void push (Object newVal) f
if (top < maxSize -1) f
top++;
store[top]=newVal;
g else f
System.err.println ("Sorry, stack is full.");
&
'
%&
$'
g
%
$
g
return ans;
g
public boolean isEmpty () f
return size() == 0;
&
g
%&
10
'
$'
Another Strategy:
Split the Difference
topChunk
0 1 2
doh ray me
N-1
...
la
0 1 2
tea doe ??
N-1
...
??
top
&
'
11
%&
$'
12
%
$
Implementing a Queue
with an Array
first
last
1
?? ray
me
far
??
N-2 N-1
...
??
??
first
&
last
%&
13
14
'
$'
Implementing a Queue
with an Array
first
N-1
N-2
??
??
??
...
last
ray
me
far
??
public ArrayQueue () f
this.maxSize = DefaultMaxSize;
store = new Object[maxSize];
...
g
public void enter (Object newElt) f
if (size() < maxSize) f
last = (last + 1) % maxSize;
store[last] = newElt;
numElements++;
g else f
System.err.println ("Sorry, queue is full.");
&
'
15
&
g
16
%&
$'
g
%&
g
17
18
%
$
'
$'
Implementing a Queue
as a Linked List
doh
ray
me
first
last
&
'
%&
$'
19
20
This program:
Misc. Notes
We have decided to declare the Node fields value and
next as package-level visible.
! This means that other classes in the same package,
such as LinkedQueue, can directly manipulate the
instance variables of each Node instance.
Also, we can use more interesting objects than Strings
and Integers in our stacks and queues.
%
$
class FigureQueueTest {
public static void main (String[] args) {
Queue q = new LinkedQueue();
Circle c1, c2;
c1 = new Circle();
c1.setSize(50);
c1.setLoc(25,30);
c2 = new Circle();
Square s1 = new Square();
s1.setSize (75);
q.enter(c1);
q.enter(c2);
q.enter(s1);
while (!q.isEmpty()) {
Figure f = (Figure) q.leave();
f.draw();
}
}
}
&
%&
21
22