【数据结构】栈

栈(Stack)是限制仅在表的一端进行插入和删除运算的线性表。 通常称插入、删除的这一端为栈顶 (Top),另一端称为栈底 (Bottom)。没有元素时称为空栈。

特点:

后进先出(Last In First Out)的线性表,简称为 LIFO 表。

Java实现

/** 
 * The Apache License 2.0
 * Copyright (c) 2018 sep6th
 */

public class Stack {

    private long[] arr;
    private int top;

    public Stack() {
        arr = new long[10];
        top = -1;
    }

    public Stack(int maxSize) {
        arr = new long[maxSize];
        top = -1;
    }

    /**
     * 压栈
     */
    public void push(int value) {
        arr[++top] = value;
    }

    /**
     * 弹栈
     */
    public long pop() {
        return arr[top--];
    }

    /**
     * 查看
     */
    public long peek() {
        return arr[top];
    }

    /**
     * 判断是否为空栈
     */
    public boolean isEmpty() {
        return top == -1;
    }

    /**
     * 判断是否为栈满
     */
    public boolean isFull() {
        return top == arr.length - 1;
    }


}

测试

/** 
 * The Apache License 2.0
 * Copyright (c) 2018 sep6th
 */

public class TestStack {

    public static void main(String[] args) {
        Stack s = new Stack(3);
        s.push(1);
        s.push(2);
        s.push(3);
        System.out.println(s.isEmpty());
        System.out.println(s.isFull());

        while(!s.isEmpty()) {
            System.out.print(s.pop() + ",");
        }

    }

}

console

false
true
3,2,1,

应用

  1. 浏览器每点击“后退”都是退回到最近一次浏览的网页。
  2. 其他

猜你喜欢

转载自blog.csdn.net/jul_11th/article/details/80480361