當前位置:編程學習大全網 - 編程軟體 - 求助:壹道編程題,如何實現java的LIFO和FIFO?編到壹半不會了

求助:壹道編程題,如何實現java的LIFO和FIFO?編到壹半不會了

接口沒改

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;

}

}

  • 上一篇:我喜歡電影方面的工作,想問下影視後期制作的有什麽工作?是指材質師,燈光師等那些,請幫我列出來
  • 下一篇:妳什麽時候改口叫對方壹半叫爸媽的
  • copyright 2024編程學習大全網