順序堆棧的實現

public class SeqStack{
	final int defaultSize = 10;
	int top;
	Object[] stack;
	int maxStackSize;
	
	public SeqStack(){
		initiate(defaultSize);
	}
	
	public SeqStack(int sz){
		initiate(sz);
	}
	
	private void initiate(int sz){
		maxStackSize = sz;
		top = 0;
		stack = new Object[sz];
	}
	
	public void push(Object obj) throws Exception{   //把數據元素obj插入堆棧
		if(top == maxStackSize){
			throw new Exception("堆棧已滿!");
		}
		stack[top] = obj;
		top ++;
	}
	
	public Object pop() throws Exception{          //出棧,刪除的數據元素由函數返回
		if(top == 0){
			throw new Exception("堆棧已空!");
		}
		top --;
		return stack[top];
	}
	
	public Object getTop() throws Exception{      //取堆棧當前棧頂的數據元素並由函數返回
		if(top == 0){
			throw new Exception("堆棧已空!");
		}
		return stack[top - 1];
	}
	
	public boolean notEmpty(){      //若當前非空則函數返回true,不然函數返回false
		return (top > 0);
	}
}
相關文章
相關標籤/搜索