作者: 小杨不是小羊 | 来源:发表于2020-12-15 23:18 被阅读0次

栈是一种操作受限的线性表,限定只能在表尾部进行插入和删除操作。
最大特点是 后进先出(LIFO)
表尾这一端被称之为栈顶,另一端叫栈底。
将一个新元素插入到栈中叫做 进栈 入栈或压栈
将一个元素从栈中删除叫做 出栈

栈.jpg
LeetCode 20 有效的括号
class Solution {
    HashMap<Character, Character> map = new HashMap<Character, Character>() {{
        put('}', '{');
        put(')', '(');
        put(']', '[');
    }};

    public boolean isValid(String s) {
        Character[] stack = new Character[100];
        int tail = -1;

        for (int i = 0; i < s.length(); i++) {
            if (map.containsKey(s.charAt(i))) {
                if (tail < 0 || stack[tail--] != map.get(s.charAt(i))) {
                    return false;
                }
            } else {
                stack[++tail] = s.charAt(i);
            }
        }
        if (tail < 0)
            return true;
        else
            return false;
    }
}
LeetCode 232 用栈实现队列

队列下篇讲

class MyQueue {

    int[] stackA = new int[100];
    int[] stackB = new int[100];
    int tailA = -1;
    int tailB = -1;

    /** Initialize your data structure here. */
    public MyQueue() {

    }

    /** Push element x to the back of queue. */
    public void push(int x) {
        stackA[++tailA] = x;

    }

    /** Removes the element from in front of queue and returns that element. */
    public int pop() {
        if (tailB < 0) {
            while (tailA >= 0) {
                stackB[++tailB] = stackA[tailA--];
            }
        }
        if (tailB < 0)
            return -1;
        return stackB[tailB--];
    }

    /** Get the front element. */
    public int peek() {
        if (tailB < 0) {
            while (tailA >= 0) {
                stackB[++tailB] = stackA[tailA--];
            }
        }
        if (tailB < 0)
            return -1;
        return stackB[tailB];
    }

    /** Returns whether the queue is empty. */
    public boolean empty() {
        if (tailA < 0 && tailB < 0)
            return true;
        return false;
    }
}

相关文章

  • Java实现栈

    数组栈:压栈、出栈、返回栈顶元素 链式栈:压栈、出栈、返回栈顶元素

  • 数据结构之 栈

    栈结构 链式栈 一.栈结构体 1构建空栈 2栈置空 3判断栈空 4获取栈顶 5入栈 6出栈 7便利栈 二.链式栈 ...

  • 栈和队列

    1、栈 栈是一种先进先出的数据结构。栈顶进栈,栈顶出栈。 数据结构 栈的初始化 进栈 出栈 栈的最小值 2、队列 ...

  • 递归累加数组

    入栈 5入栈 4入栈 3入栈 2入栈 1出栈 [1 0]出栈 [2 1 0]出栈 [3 2 1 0]出栈 [4 3...

  • 栈的逻辑结构和存储结构

    main()进栈s(1)进栈s(0)进栈 s(0)出栈s(1)出栈main()出栈 顺序栈 一个数组 + 指向栈顶...

  • 单调栈 2020-06-12(未经允许,禁止转载)

    1.单调栈 指栈内元素保持单调性的栈结构,分为单调增栈(栈底到栈顶元素递增)和单调减栈(栈底到栈顶元素递减) 2....

  • 链栈的操作

    链栈的定义 链栈的操作 初始化 判断栈空 入栈 出栈

  • 函数调用栈平衡

    栈平衡 栈平衡:函数调用前后的栈顶指针指向的位置不变 内平栈 外平栈 内平栈: 指的是在函数调用返回之前使栈保持...

  • 栈的简单Java实现

    栈栈的特点是先进后出,出栈、入栈都是在栈顶操作。

  • 汇编学习-入栈和出栈

    栈有两个基本的操作:入栈和出栈。入栈就是将一个新的元素放到栈顶,出栈就是从栈顶取出一个元素。栈顶的元素总是最后入栈...

网友评论

      本文标题:

      本文链接:https://www.haomeiwen.com/subject/zmibgktx.html