栈是一种操作受限的线性表,限定只能在表尾部进行插入和删除操作。
最大特点是 后进先出(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;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 栈和队列 栈和队列的定义和特点 栈的定义和特点 栈(stack): 是限定仅在表尾(栈顶)进行插入或删除操作的线性...
    卖渔翁阅读 615评论 0 2
  • 4.2.1 栈的定义 栈是限定仅在表尾进行插入和删除操作的线性表 我们把允许插入和删除的一端称为栈顶,另一端称为栈...
    镜花水月阅读 269评论 0 0
  • 一.栈 1.栈的定义 栈是仅在表尾进行插入和删除操作的线性表允许插入和删除的一段称为栈顶(top),另一端称为栈底...
    e40c669177be阅读 535评论 5 1
  • 预备知识—程序的内存分配 一个由C/C 编译的程序占用的内存分为以下几个部分:1、栈区(stack)—> 由编译器...
    绚雨蓝了个枫阅读 4,339评论 0 3
  • 栈是限定仅在表尾进行插入和删除操作的线性表。队列是只允许在一端进行插入操作,而在另一端进行删除操作的线性表。 栈的...
    Yix1a阅读 545评论 0 0