如何在java中实现队列?

时间:2017-06-19 18:11:27

标签: java queue

我想在此代码中执行与堆栈相同的操作 我怎么能改变它所以它将成为队列?我不想为那个

使用stack或LinkedList
    public StackAsArray(){
        this(new DynamicArray());
    }
    public boolean isEmpty() {

    }
    public void push(Object o) {

    }
    public Object pop() {

    }
}

1 个答案:

答案 0 :(得分:1)

您只需要使用pushpop方法替换enqueuedequeue方法。

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;
    }
}