我目前正在處理一個 Stack 項目,我正在其中創建一個泛型 Stack 類。我一直在尋找堆棧溢出,但找不到它。我需要幫助在我的代碼中創建一個pop方法。以下是我到目前為止所擁有的:public class Stack<E>{public static final int DEFAULT_CAPACITY = 10;private E [] elementData;private int size;@SuppressWarnings("unchecked")public Stack(){ this.elementData = (E[]) new Object[DEFAULT_CAPACITY];}@SuppressWarnings("unchecked")public Stack(int capacity){ if(capacity < 0) { throw new IllegalArgumentException("capacity " + capacity); } this.elementData = (E[]) new Object[capacity];}public boolean isEmpty(){ if(size == 0) { return true; } else { return false; }}/*The push method should add its parameter to the top of the stack.*/public void push(E item){ ensureCapacity(size+1); elementData[size] = item; size++;}private void ensureCapacity(int capacity) { if(elementData.length < capacity) { int newCapacity = elementData.length * 2 + 1; elementData = Arrays.copyOf(elementData, newCapacity); }}我在這里需要幫助。我需要讓pop方法刪除并返回堆棧頂部的元素。如果不存在任何項目,它應該拋出一個“EmptyStackException”。 public E pop() { if(isEmpty()) { throw EmptyStackException } else { }}}
2 回答

喵喵時光機
TA貢獻1846條經驗 獲得超7個贊
我想通了,我把功勞歸于@ScaryWombat。代碼是:
public E pop()
{
if(isEmpty())
{
throw new EmptyStackException();
}
else
{
return elementData[--size];
}
}

慕萊塢森
TA貢獻1810條經驗 獲得超4個贊
public E pop()
{
E item;
if(isEmpty())
{
throw new EmptyStackException();
}
else
{
item = elementData[size];
size--;
}
return item;
}
您需要使返回變量等于堆棧數組的頂部,然后遞減堆棧數組。此外,您需要通過設置 size=0 來初始化堆棧。
添加回答
舉報
0/150
提交
取消