2017-06-19 98 views
-1

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

public StackAsArray(){ 
     this(new DynamicArray()); 
    } 
    public boolean isEmpty() { 

    } 
    public void push(Object o) { 

    } 
    public Object pop() { 

    } 
} 
+2

通过考虑你的家庭作业和尝试。而不是倾销一些代码和要求。 – GhostCat

回答

1

你只需要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; 
    } 
}