题目描述

用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。

使用栈实现队列的下列操作:push(x) -- 将一个元素放入队列的尾部pop() -- 从队列首部移除元素peek() -- 返回队列首部的元素empty() -- 返回队列是否为空。

你只能使用标准的栈操作 -- 也就是只有 push to top, peek/pop from top, size, 和 is empty 操作是合法的。

编程思想

由于队列是先进先出的,而栈是先进后出的,所以要用2个栈来实现队列的入队出队功能。队列的入队,与栈的一样。队列的出队,先将第一个栈中的元素全部弹出,并倒入到第二个栈中,将第二个栈中栈顶元素弹出,并将stack2中剩下的元素倒回到stack1中,即实现一次出队。

编程实现

class MyQueue {
public:
/** Initialize your data structure here. */ stack<int> s1, s2; MyQueue() { } /** Push element x to the back of queue. */
void push(int x) {
while(!s2.empty()) {
s1.push(s2.top());
s2.pop();
}
s2.push(x);
while(!s1.empty()) {
s2.push(s1.top());
s1.pop();
}
} /** Removes the element from in front of queue and returns that element. */
int pop() {
int a = s2.top();
s2.pop();
return a;
} /** Get the front element. */
int peek() {
return s2.top();
} /** Returns whether the queue is empty. */
bool empty() {
return s2.empty();
}
};

题目总结

掌握队列和栈的特性。

最新文章

  1. shell循环
  2. DrawerLayout的使用
  3. CentOS 6.4 快速安装Nginx笔记
  4. 【leetcode】Interleaving String
  5. POJ 1656
  6. C#调用C、C++结构体数组的方法总结
  7. MVC @Html.DropDownListFor 默认值
  8. 【原】window上安装elasticserach
  9. cut 命令使用
  10. HTML5触摸屏touch事件使用介绍1
  11. 【专访】【Spring常见问题汇总】【05】
  12. 初识JSON
  13. .NET技术面试题系列(1) 基础概念
  14. 【构造】UVa 11387 The 3-Regular Graph
  15. this.setData , that.setData , this.data.val三者之间的区别和作用
  16. .net数据库实现Excel的导入与导出
  17. git批量恢复所有删除的文件
  18. 在使用 #import &lt;objc/message.h&gt;时 xcode 报 :Too many arguments to function call, expected 0 , have * 解决方法
  19. php判断是否为时间戳
  20. 【转载】Gradle构建多模块项目

热门文章

  1. maven私有仓库搭建(nexus)
  2. 后台运行程序nohup的使用
  3. Java程序执行过程及内存机制
  4. js生成随机数、随机数列、数值转金融格式
  5. java中什么是对象,什么是对象引用
  6. Android 7.0应用之间共享文件
  7. 用Python实现童年的回忆:俄罗斯方块!别说还挺好玩
  8. Docker实例开机启动
  9. Java基础-方法的重写和重载
  10. win10开启运行下显示历史操作记录