我想在此代码中执行与堆栈相同的操作 我怎么能改变它所以它将成为队列?我不想为那个
使用stack或LinkedList public StackAsArray(){
this(new DynamicArray());
}
public boolean isEmpty() {
}
public void push(Object o) {
}
public Object pop() {
}
}
答案 0 :(得分:1)
您只需要使用push
和pop
方法替换enqueue
和dequeue
方法。
enqueue
会在数组末尾添加元素,而dequeue
会从一开始就删除它。
public class QueueAsArray implements Queue {
...
public void enqueue(Object o) {
arr.set(numOfElements, o);
numOfElements++;
}
public Object dequeue() {
if(isEmpty()) { // an empty check is a MUST
return null;
}
numOfElements = numOfElements - 1;
Object res = arr.get(0);
arr.set(0, null); // not 100% sure this works, but since this is a homework question, its upto you to figure out. The logic is to remove the 0th element.
return res;
}
}