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();
}
}
}
}