注意构造器的写法,top初始为-1
public class MyStack
{
private int[] arr;
private int top;
private int size;
//构造器
public MyStack(int size){
this.arr = new int[size];
this.size = size;
this.top = -1;
}
//判空
public boolean isEmpty(){
return top == -1;
}
//判满
public boolean isFull(){
return top==size - 1;
}
//入栈
public void push(int val){
if(isFull()){
System.out.println("栈已满!");
return;
}
top++;
arr[top] = val;
}
//出栈
public int pop(){
if(isEmpty()){
System.out.println("栈为空!");
return 0;
}
return arr[top--];
}
//返回栈顶内容
public int peek(){
if(isEmpty()){
System.out.println("栈为空!");
}
return arr[top];
}
//打印整个栈
public void print(){
for(int i=top;i>=0;i--){
System.out.println(arr[i]+" ");
}
}
//测试
public static void main(String[] args){
MyStack stack = new MyStack(10);
stack.push(3);
stack.push(6);
stack.push(9);
System.out.println("栈中内容为:");
stack.print();
System.out.println("栈顶为:"+stack.peek());
System.out.println("出栈后,栈中内容为:");
stack.pop();
stack.print();
}
}