LIFO的
class LIFOBag implements Bag {
private Object[] stack;
private int stackTop = 0;
public LIFOBag(int size) {
stack = new Object[size];
}
public void add(Object thing) {
if (stackTop == stack.length - 1) {
throw new RuntimeException("stack overflow!");
} else {
stackTop++;
stack[stackTop] = thing;
}
}
public Object remove() {
Object o;
if (stackTop == 0) {
o = null;
} else {
o = stack[stackTop];
stackTop--;
}
return o;
}
public static void main(String[] args) {
Bag bag = new LIFOBag(50);
for(int i = 0; i< 50; i++) {
bag.add(i);
Object o = bag.remove();
System.out.println(o);
}
}
}
FIFO的
class FIFOBag implements Bag {
private Object[] queue;
private int first = 0;
private int last = 0;
public FIFOBag(int size) {
queue = new Object[size];
}
/* 模擬循環隊列 */
public void add(Object thing) {
if (first == last + 1 || (first == 0 && last == queue.length-1)) {
throw new RuntimeException("queue overflow!");
} else {
// 向隊尾添加
last++;
if(last == queue.length) {
last = 0;
}
queue[last] = thing;
}
}
public Object remove() {
Object o;
if (first == last) {
o = null;
} else {
o = queue[first];
first++;
if(first == queue.length) {
first = 0;
}
}
return o;
}
}