1.代码
 
1.
 
package com.example.lib5.stack;
public class ArrayStackDemo {
    public static void main(String[] args) {
        ArrayStack arrayStack = new ArrayStack(10);
        boolean isFull=arrayStack.isFull();
        System.out.println("是否满了"+isFull);
        boolean isEmpty=arrayStack.isEmpty();
        System.out.println("是否为空"+isEmpty);
        arrayStack.push(2);
        arrayStack.push(3);
        arrayStack.push(4);
        arrayStack.push(5);
        arrayStack.push(8);
        int pop = arrayStack.pop();
        System.out.println("取出的值为"+pop);
        arrayStack.list();
    }
}
class ArrayStack{
    private int maxSize;
    private int[] stack;
    private int top=-1;
    public ArrayStack(int maxSize) {
        this.maxSize=maxSize;
        stack = new int[maxSize];
    }
    public boolean isFull() {
        return top==maxSize-1;
    }
    public boolean isEmpty() {
        return top==-1;
    }
    public void push(int value) {
        
        if (isFull()) {
            System.out.println("满了无法添加");
            return;
        }
        
        top++;
        stack[top]=value;
    }
    public int pop() {
        
        if (isEmpty()) {
            throw new RuntimeException("栈空,没有数据");
        }
        int value=stack[top];
        
        stack[top]=0;
        top--;
        return value;
    }
    public void list() {
        
        if (isEmpty()) {
            System.out.println("为空");
            return;
        }
        
        System.out.println("遍历结果为-----------------------");
        for (int i = top; i > -1; i--) {
            System.out.println("遍历结果为"+stack[i]);
        }
    }
}
 
2.描述
 
1.栈有先进后出的特点,即进去1,2,3,出来就是3,2,1。跟队列是反过来的(队列是先进先出)
 
2.用数组实现栈,MaxTop表示最大值,Top表示栈里有多少个值,每次添加一就会top++,top=MaxTop-1的时候表示满了,top=-1表示栈空
 

 
3.反思总结
 
1.
 
2.
 
3.
 
4.
 
5.
 
6.