JAVA 实现一个简单的堆栈

public  Stack{

int[] data;

int maxSize;

int top;

public Stack(int maxSize){

this.maxSize = maxSize; //数组长度

data = new int[maxSize];

top = -1;  //设置空栈

}

//压栈

public  boolean push(int data){

if(top == maxSize-1){

   throw new RuntimeException("栈已满”);

 }else{

  this.data[top++] = data;

  return true;

}

//弹出

public int pop throw Exception(){

 if(top == -1){

throw new RuntimeException(“栈已空”)

}

}

}

}

//测试

class Test(){

public static void main(){

 Stack stack = new Stack(6);

stack.push(1);

stack.push(2);

stack.push(3);

stack.push(4);

stack.push(5);

stack.push(6);

while(stack.top >=0){

System.out.print(stack.pop())

}

}

}

猜你喜欢

转载自blog.csdn.net/qq_38233650/article/details/88017254