package data;
/**使用数组实现栈
* @author Babulakaka
* @create 2021-06-13 9:47
*/
public class StackDemo {
public static void main(String[] args) {
ArrayStack stack = new ArrayStack(5);
stack.push(1);
stack.push(2);
stack.push(3);
stack.push(4);
stack.push(5);
stack.show();
System.out.println("出栈:"+stack.pop());
System.out.println("出栈:"+stack.pop());
System.out.println("出栈:"+stack.pop());
System.out.println("出栈:"+stack.pop());
}
}
class ArrayStack{
public int[]arr;
public int maxSize;
public int top=-1;
ArrayStack(int maxSize){
this.maxSize=maxSize;
arr = new int[this.maxSize];
}
//判断栈满
public boolean isFull(){
return top==maxSize-1;
}
//判断栈空
public boolean isEmpty(){
return top==-1;
}
//出栈
public int pop(){
if(isEmpty()){
throw new RuntimeException("栈空,无法出栈");
}
return arr[top--];
}
//入栈
public void push(int n){
if(isFull()){
System.out.println("栈满,无法入栈");
}
arr[++top]=n;
System.out.println(n+"成功入栈");
}
//展示栈
public void show(){
for(int i=0;i<maxSize;i++){
System.out.println("stack["+i+"]="+arr[i]);
}
}
}
使用数组实现自定义栈
最新推荐文章于 2021-08-24 17:12:21 发布