java使用数组实现栈

数组实现栈:

实现判断是否为满了isFull()、入栈push、出栈pop、展示栈list

/**
 * @author xin麒
 * @date 2022/4/1
 */
public class XinStack {
    int top = -1;
    int[] intlist;
    int maxSize;

    public XinStack(int maxSize) {
        this.maxSize = maxSize;
        intlist = new int[maxSize];
    }

    public boolean isFull(){
        return top == maxSize - 1;
    }
    public void push(int value){
        if (!isFull()){
            top++;
            intlist[top] = value;
        }else {
            System.out.println("stack is full");
        }
    }

    public int pop(){
        if (top > -1){
            int value = intlist[top];
            top--;
            return value;
        }else {
            throw new RuntimeException("元素已经没有了");
        }
    }
    public void list(){
        if (maxSize < 0){
            return;
        }
        for (int i = top; i >= 0 ; i--) {
            System.out.printf(intlist[i] + " ");
        }
        System.out.print("\n");
    }
}

后面xin麒将会使用链表实现栈

你可能感兴趣的:(java,leetcode,算法,java)