Java Stack栈

栈的概念

栈: 一种特殊的线性表,其只允许在固定的一端进行插入和删除元素操作。

栈中的数据元素遵守后进先出LIFO(Last In First Out)的原则。

压栈:栈的插入操作叫做进栈/压栈/入栈,入数据在栈顶。

出栈:栈的删除操作叫做出栈。出数据在栈顶。

Stack继承了Vector,Vector和ArrayList类似,都是动态的顺序表,不同的是Vector是线程安全的

 栈的使用

import java.util.Stack;

public class TestDemo {
    public static void main(String[] args) {
        Stack<Integer> stack = new Stack<>();
        stack.push(12);
        stack.push(23);
        stack.push(34);
        stack.push(45);
        System.out.println(stack.size());
        stack.pop();
        int ret = stack.peek();
        System.out.println(ret);
        System.out.println(stack.empty());
        System.out.println(stack.size());
        System.out.println(stack);
    }
}

 

栈的模拟实现

import java.util.Arrays;

public class MyStack {
    public int[] elem;
    //不仅可以记录 你当前的元素的个数
    // 还可以当做当前可以存放元素的下标
    public int usedSize;

    public MyStack() {
        this.elem = new int[10];
    }

    public void push(int val) {
        if(isFull()) {
            //扩容
            this.elem = Arrays.copyOf(this.elem,2*this.elem.length);
        }
        this.elem[usedSize] = val;
        usedSize++;
    }

    public boolean isFull() {
        return this.usedSize == this.elem.length;
    }

    public int pop() {
        if(empty()) {
            throw new RuntimeException("栈为空!");
        }
       /* int val = this.elem[usedSize-1];
        this.usedSize--;
        return val;*/
        this.usedSize--;
        return this.elem[usedSize];
    }

    public int peek() {
        if(empty()) {
            throw new RuntimeException("栈为空!");
        }
        return this.elem[usedSize-1];
    }

    public boolean empty() {
        return this.usedSize == 0;
    }

    public int size() {
        return this.usedSize;
    }
}

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值