java 陣列實現棧
java實現棧
package ReviewBook;
public class Stacktest {
int[] data;
private int size;
private int top;
public Stacktest(int size){
this.size=size;//構造方法
data=new int[size];//初始化陣列
top=-1;//初始化棧頂
}
public int getSize()
{
return size;
}
public int getTop()
{
return top;
}
//判斷是否是空棧
public boolean isEmpty()
{
return top == -1;//判斷top是否是-1,如果是-1則返回true
}
public boolean isFull(){
return (top+1)==size;
}
//壓棧操作
public boolean push(int data)
{if(isFull())
{System.out.println("棧滿了");
return false;
}else{
top++;
this.data[top]=data;
return true;
}
}
//彈棧操作 定義一個新的異常 在程式中丟擲
public int pop() throws Exception
{
if(isEmpty()){
throw new Exception("棧為空");
}else{
return this.data[top--];
}
}
public int peek()
{
return this.data[top];
}
public static void main(String[] args) {
Stacktest st=new Stacktest(20);
st.push(1);
st.push(2);
st.push(3);
System.out.println("現在棧頂是"+st.peek());
while(!st.isEmpty()){
try {
System.out.println(st.pop());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}