如何在java中实现队列?

我想在堆栈的代码中做同样的事情 我该如何更改它,以便将它用于队列?我不希望使用堆栈或链表为如何在java中实现队列?

public StackAsArray(){ 

this(new DynamicArray());

}

public boolean isEmpty() {

}

public void push(Object o) {

}

public Object pop() {

}

}

回答:

你只需要enqueuedequeue方法来取代你pushpop方法。

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;

}

}

以上是 如何在java中实现队列? 的全部内容, 来源链接: utcz.com/qa/258517.html

回到顶部