[英]I'm not sure how to make this stack implementation dynamic
首先,如果這是一個非常明顯的問題,或者我沒有正確看待它,我深表歉意。 我被指示“將棧擴展為動態的”。 我已獲得有關如何執行此操作的具體說明,即:
使新的數組tmp大小是當前數組的兩倍
將當前數組的所有元素(在講義中稱為S)復制到tmp中
設置S = tmp;
應該執行此操作的代碼塊將放入push()方法中,替換異常引發部分。
問題是,我不知道我應該使用哪種數組(泛型只是最近才引入我的,而我對此並不十分了解)。 有什么明顯的我想念的東西嗎?
我沒有編寫大部分代碼,只有pop(),push()和top()方法。
public class ArrayStack<E> implements Stack<E> {
private E[] S;
private int top;
private int capacity;
private static int DEFAULT_SIZE = 100;
public ArrayStack(int size){
capacity = size;
S = (E[]) new Object[size];
top = -1;
}
public ArrayStack(){
this(DEFAULT_SIZE);
}
public E pop() throws StackException{
if(isEmpty())
throw new StackException("stack is empty");
return S[top--];
}
public void push(E e) throws StackException{
if (size() == capacity)
throw new StackException("Stack is full");
S[++top] = e;
}
public E top() throws StackException{
if(isEmpty())
throw new StackException("Stack is empty");
return S[top];
}
查看您的代碼,看來該數組應該是E
對象。
使用Java泛型,可以使用(E[]) new Object[2 * initial_size]
創建此數組
這些說明希望您在push中查看下面的代碼段
if (size() == capacity)
throw new StackException("Stack is full");
並沒有付出太多,因為這是一個任務
if (size() == capacity)
Make a new array tmp of twice the size of the current array
Copy all elements the current array (called S in the lecture notes) into tmp
S = tmp;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.