数组实现栈

先进后出。push入栈,pop出栈,peek查看栈顶元素。数组实现栈有栈空,栈满。

数组实现栈
package com.simple.st;

/**
 * @ClassName Stack
 * @Author gg_girl
 * @Date 2020/9/4
 * @Description 栈类。有栈空,栈满。
 * 操作:入栈push,出栈pop,peek查看栈顶元素,栈空,栈满判断,元素展示
 * @Version 1.0
 */
public class Stack {
    public int size;
    public int top;
    public int[] array;
    public Stack(int size){
        this.size = size;
        this.top = -1; // -1栈空
        this.array = new int[this.size];
    }
    public void push(int ele){
        // push前判断栈是否满
        this.array[++top] = ele;
    }
    public int pop(){
        return this.array[top--];
    }

    public int peek(){
        return this.array[top];
    }

    public boolean isEmpty(){
        return this.top == -1;
    }

    public boolean isFull(){
        return this.top == this.size - 1;
    }

    public void display() {
        for(int i = 0; i <= this.top; i++){
            System.out.print(this.array[i] + "  ");
        }
        System.out.println();
    }
}

package com.simple.st;

/**
 * @ClassName StackApp
 * @Author gg_girl
 * @Date 2020/9/4
 * @Description Stack类应用及测试
 * @Version 1.0
 */
public class StackApp {
    public static void main(String[] args) {
        Stack stack = new Stack(4);
        stack.push(1);
        stack.push(2);
        stack.push(3);
        stack.push(4);// 1 2 3 4
        System.out.println(stack.isFull());//true
        stack.display();// 1 2 3 4
        int ele = stack.pop(); // 4
        System.out.println(ele);
        stack.pop();//3
        stack.pop(); // 2
        stack.pop(); // 1
        System.out.println(stack.isEmpty()); // true

    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值