0
点赞
收藏
分享

微信扫一扫

Java Stack栈

您好 2022-03-25 阅读 67

栈的概念

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

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;
    }
}
举报

相关推荐

0 条评论