博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
用双栈实现队列(java)
阅读量:3952 次
发布时间:2019-05-24

本文共 2627 字,大约阅读时间需要 8 分钟。

在这里插入图片描述在这里插入图片描述out 栈相当于一个缓冲区域,把一部分入队的放到这个缓冲区域

当你拿出头元素的时候就可以直接去缓冲区去拿了,效率高,
LeetCode官网还给出了第二种解法,用到了均摊复杂度的知识,展示还没搞懂,这里介绍是方法一

class MyQueue {        Stack
input; Stack
output; /** Initialize your data structure here. */ public MyQueue() { input = new Stack(); output = new Stack(); } /** Push element x to the back of queue. */ public void push(int x) { input.push(x); } /** Removes the element from in front of queue and returns that element. */ public int pop() { if(!output.isEmpty()) { return output.pop(); }else { while(!input.isEmpty()) { output.push(input.pop()); } return output.pop(); } } /** Get the front element. */ public int peek() { if(!output.isEmpty()) { return output.peek(); }else { while(!input.isEmpty()) { output.push(input.pop()); } return output.peek(); } } /** Returns whether the queue is empty. */ public boolean empty() { return output.isEmpty()&&input.isEmpty(); }}/** * Your MyQueue object will be instantiated and called as such: * MyQueue obj = new MyQueue(); * obj.push(x); * int param_2 = obj.pop(); * int param_3 = obj.peek(); * boolean param_4 = obj.empty(); */下面是双队列实现

队列实现栈

我对这道题的理解是,准备两个队列,我分别命名为 input,队列和output 队列

output队列的第一位始终是最后一个进队列的,因此,每一次弹栈,都是弹出最后那个进队列的,这样就可以模拟栈的特性了 具体代码如下 `

class MyStack {Queue
input;Queue
output;/** Initialize your data structure here. */public MyStack() { input = new LinkedList(); output = new LinkedList(); }/** Push element x onto stack. */public void push(int x) { if(output.size()==0) { output.offer(x); }else { while(output.size()!=0) { input.offer(output.poll());//清空 output 队列 } output.offer(x); //进队的放在output队列的第一位 while(input.size()!=0) { output.offer(input.poll());//重改output 队列 } } }/** Removes the element on top of the stack and returns that element. */public int pop() { if(output.peek()==null) { return 0; } return output.poll(); }/** Get the top element. */public int top() { if(output.peek()==null) { return 0; } return output.peek();}/** Returns whether the stack is empty. */public boolean empty() { return output.peek()==null;}}

作者:deep-dark

链接:

转载地址:http://vbyzi.baihongyu.com/

你可能感兴趣的文章
总结过去2017年最受欢迎的十大机器学习Python库
查看>>
恕我直言,你可能被支付宝账单预测关键词骗了!
查看>>
2018年春运火车票今天开售,手把手教你用Python抢票回家过年....
查看>>
【精华】大数据在营销中的6大优势
查看>>
炫!把你的生活轨迹用大数据展示后.......惊呆了~
查看>>
透过震惊世界的数据,探索中国数字化生态及潜力
查看>>
开发者必读:计算机科学中的线性代数(附论文)
查看>>
大数据下的帝都魔都的爱恨情仇
查看>>
GitHub最著名的20个Python机器学习项目!
查看>>
小白都能看懂的神经网络入门,快收下吧~
查看>>
这十大挑战,摆在深度学习面前(附论文)
查看>>
用Python分析李小璐微博.........贾乃亮到底.........
查看>>
教你用一行Python代码实现并行(附代码)
查看>>
Google发布了2017年最常被搜索的一个词,竟然看哭了几亿人
查看>>
学习 Python 编程的 19 个资源
查看>>
收藏!超全机器学习资料合集!(附下载)
查看>>
搞笑动图:这些痛,只有程序员懂…
查看>>
不学Python的同学,“跳一跳”都输了
查看>>
资源:惊艳全球数据行业的16个数据可视化例子
查看>>
先搞懂这八大基础概念,再谈机器学习入门!
查看>>