数组模拟栈

public class MyStack {


private int top;

    private int[] arr;


    public MyStack(int size) {


arr = new int[size];


}




public boolean isEmpty() {


return top == 0;



}



public boolean isFull() {


return top == arr.length;


}



public void push(int data) {



if(isFull()){


throw new RuntimeException("数据满了");


}



arr[top++] = data;




}



public int pop() {


if(isEmpty()){


System.out.println("空了");

          throw new RuntimeException("没数据了");


}


return arr[--top];



}



public int size() {


return top;


}


public static void main(String[]args){


MyStack myStack = new MyStack(6);


myStack.push(1);


myStack.push(2);


myStack.push(3);


myStack.push(4);


myStack.push(5);


myStack.push(6);



System.out.println("pop:"+myStack.pop());


System.out.println("size:"+myStack.size());


//    System.out.println("pop:"+myStack.pop());

//    System.out.println("pop:"+myStack.pop());

//    System.out.println("pop:"+myStack.pop());

//    System.out.println("pop:"+myStack.pop());



}

}

你可能感兴趣的:(数组模拟栈)