創(chuàng)建ResizeArrayStack
實(shí)現(xiàn)Iterable
接口使得ResizeArrayStack
能夠被迭代崭倘,用Item代替所有的數(shù)據(jù)類型祥楣。
public class ResizeArrayStack<Item> implements Iterable<Item>
//創(chuàng)建存放數(shù)據(jù)的數(shù)組(棧)
private Item[] stack = ((Item[])new Object[1]);
//記錄棧中的元素個數(shù),指明棧頂元素的位置(count-1)
private int count = 0;
//判斷棧是否為空
public boolean isEmpty(){
return count == 0;
}
//返回迭代器,可用于迭代棧元素
@Override
public Iterator<Item> iterator() {
return new ResizeArrayStackIterator();
}
/**
* 重置數(shù)組的大小
*/
private void resize(int max){
Item[] newStack = (Item[]) new Object[max];
for(int i = 0; i < stack.length; i ++){
newStack[i] = stack[i];
}
stack = newStack;
}
//入棧操作
public void push(Item item){
if(count == stack.length){
resize(stack.length * 2);
}
stack[count++] = item;
}
/**
* 出棧操作
* @return
*/
public Item pop(){
Item topItem = stack[--count];
stack[count] = null;
if(count >0 && count == stack.length/4)
resize(stack.length/2);
return topItem;
}
//創(chuàng)建迭代器
class ResizeArrayStackIterator implements Iterator<Item>{
int i = count;
@Override
public boolean hasNext() {
return i > 0;
}
@Override
public Item next() {
return stack[--i];
}
@Override
public void remove() {
}
}