博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode 232. Implement Queue using Stacks
阅读量:7071 次
发布时间:2019-06-28

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

方法一:利用两个栈,每次push都利用另一个栈倒一遍。其中push O(n)

class MyQueue {private:    stack
s1; //the same order of queue stack
s2;public: /** Initialize your data structure here. */ MyQueue() { } /** Push element x to the back of queue. */ void push(int x) { while (!s1.empty()){ int tmp=s1.top(); s1.pop(); s2.push(tmp); } s2.push(x); while (!s2.empty()){ int tmp=s2.top(); s2.pop(); s1.push(tmp); } } /** Removes the element from in front of queue and returns that element. */ int pop() { int tmp=s1.top(); s1.pop(); return tmp; } /** Get the front element. */ int peek() { return s1.top(); } /** Returns whether the queue is empty. */ bool empty() { return s1.empty(); }};/** * 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(); * bool param_4 = obj.empty(); */

 

方法二:同样是利用两个栈,但是不同于上一种方法每次push都要倒一次。两个栈记作in和out,out顺序与queue一致。每次push都放到in中,需要pop的时候才把in倒到out中执行。相当于in作为一个缓存,out没元素了才将in中的元素倒入out中。push-O(1); pop-Amortized O(1)。

详见 

class MyQueue {private:    stack
in; stack
out; int front;public: /** Initialize your data structure here. */ MyQueue() { } /** Push element x to the back of queue. */ void push(int x) { if (in.empty()) front=x; in.push(x); } /** Removes the element from in front of queue and returns that element. */ int pop() { if (out.empty()){ //move from in to out while (!in.empty()){ out.push(in.top()); in.pop(); } } int tmp=out.top(); out.pop(); return tmp; } /** Get the front element. */ int peek() { if (!out.empty()) return out.top(); else return front; } /** Returns whether the queue is empty. */ bool empty() { return in.empty() && out.empty(); }};/** * 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(); * bool param_4 = obj.empty(); */

 

转载于:https://www.cnblogs.com/hankunyan/p/9520766.html

你可能感兴趣的文章
DW快速去除tppabs冗余代码
查看>>
Java8新特性之:新的日期和时间API
查看>>
如何才能从程序员成长为实战型架构师?必掌握这7大实战技能经验
查看>>
rabbitMQ集群的搭建和维护第二篇---利用python程序完成mq的消息收发和实时监控
查看>>
网众设置开机重启服务的命令,才可连接BOOT服务器
查看>>
RHEL6.3 DNS配置详解一 DNS相关概念理解及配置基础
查看>>
Windows环境 和 Linux环境下搭建Qt开发环境
查看>>
简述synchronized和java.util.concurrent.locks.Lock的异同
查看>>
在win2008r2下开启ntp服务
查看>>
我的友情链接
查看>>
SpringMVC源码解析(三)——HandlerAdapter
查看>>
Python执行系统命令的方法
查看>>
动态加载远程Jar的实现方式
查看>>
无线***笔记(一)-《***WPA-PSK加密无线网络》
查看>>
MyEclipse10.1集成SVN
查看>>
Sitemesh和Struts2结合时Filter的配制顺序
查看>>
【python】编程语言入门经典100例--19
查看>>
[tomcat7源码学习]ClassLoader加载Tomcat的依赖
查看>>
解决MySQL Master/Slave 同步出错
查看>>
常用的主机监控Shell脚本
查看>>