首页 > 其他 > 详细

【40讲系列2】栈、队列

时间:2020-11-19 22:36:47      阅读:47      评论:0      收藏:0      [点我收藏+]

一、栈和队列的特点,使用场景

栈(Stack)是限定仅在表尾进行插入和删除操作的线性表,后进先出。

队列(Queue)是只允许在一端进行插入操作,而在另一端进行删除操作的线性表,先进先出。

二、典型例题

①:判断括号字符串是否有效

LeetCode20-括号的匹配

②:用栈实现队列(LC232、剑指05.用两个栈实现队列

③:用队列实现栈(LC225)

class MyStack {

    Queue<Integer> queue;
    /** Initialize your data structure here. */
    public MyStack() {
        queue = new LinkedList<>();
    }
    
    /** Push element x onto stack. */
    public void push(int x) {
        queue.offer(x);
        for (int i = 0; i < queue.size() - 1; i++) {
            queue.offer(queue.poll());
        }
    }
    
    /** Removes the element on top of the stack and returns that element. */
    public int pop() {
        return queue.poll();
    }
    
    /** Get the top element. */
    public int top() {
        return queue.peek();
    }
    
    /** Returns whether the stack is empty. */
    public boolean empty() {
        return queue.isEmpty();
    }
}

 

【40讲系列2】栈、队列

原文:https://www.cnblogs.com/HuangYJ/p/12837542.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!