import java.util.*;
import java.lang.Iterable;
public class MyStackArray <Item> implements Iterable<Item> {
private Item I[];
private int top;
private int size;
private final static int DEFAULT_SIZE = 10;
public MyStackArray () {
this(DEFAULT_SIZE);
}
public MyStackArray (int capacity) {
size = capacity;
I = (Item[]) new Object [capacity];
top = -1;
}
public Item getTop() {
if (isEmpty())
return null;
return I[top];
}
public boolean isEmpty() {
return (top == -1);
}
public boolean isFull() {
return (top == I.length - 1);
}
public Item pop() throws EmptyStackException {
if (isEmpty())
throw new EmptyStackException ();
Item item = I[top];
I[top--] = null;
if(top> 0 && top== I.length / 4)
resize(I.length/2);
return item;
}
public void push(Item item) throws FullStackException {
if (isFull())
throw new FullStackException ();
if (top== I.length - 1)
resize(2 * I.length);
I[++top] = item;
}
public int size() {
return (top+ 1);
}
private void resize (int newCapacity) {
Item t[] = (Item[]) new Object[newCapacity];
for (int i = 0; i <= top; i++)
t[i] = I[i];
I = t;
}
public Iterator<Item> iterator() {
return new MyStackArrayIterator();
}
private class MyStackArrayIterator implements Iterator <Item> {
private int i = top;
public boolean hasNext() {
return (i > -1);
}
public Item next() {
return I[i--];
}
public void remove() {
throw new UnsupportedOperationException();
}
}
}
这是Stack使用泛型方法的代码。对于isEmpty,一切都很顺利,异常是工作的。
public boolean isFull() {
return (top == I.length - 1);
}
我应该怎么改变,isFull()和push()异常可以正常工作?在驱动程序类中,当元素的最大值为5时,我试图推5个元素。
push("A");push("B");push("C");push("D");push("E");
size() = 5, getTop() = E
然后再压入一个元素,异常提示堆栈已满。
size() = 5, getTop() = E
所以,我把它们都摘了。
Size = 0, getTop = null
我推了3个元素,
push("F");push("G");push("H");
但是程序说堆栈已经满了,而最大值是5个元素。我怎样才能解决这个问题呢?
当您弹出大多数元素(当top== I.length / 4
)时,您的pop
方法将堆栈的容量减半。
你的push
方法应该在必要时增加容量,但isFull()
阻止它这样做(因为isFull()
检查的相同条件- (top == I.length - 1)
-也被用来确定何时应该增加容量)。
如果您支持增加容量,isFull()
意味着什么?容量要么是固定的,在这种情况下,你不应该改变它,要么是不固定的,在这种情况下,isFull()
应该总是返回false。