2017-06-19 118 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; 
    } 
}