剑指offer 面试题9:用两个栈实现队列
2024-10-19 03:34:43
题目描述
用两个栈来实现一个队列,完成队列的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();
}
};
题目总结
掌握队列和栈的特性。
最新文章
- shell循环
- DrawerLayout的使用
- CentOS 6.4 快速安装Nginx笔记
- 【leetcode】Interleaving String
- POJ 1656
- C#调用C、C++结构体数组的方法总结
- MVC @Html.DropDownListFor 默认值
- 【原】window上安装elasticserach
- cut 命令使用
- HTML5触摸屏touch事件使用介绍1
- 【专访】【Spring常见问题汇总】【05】
- 初识JSON
- .NET技术面试题系列(1) 基础概念
- 【构造】UVa 11387 The 3-Regular Graph
- this.setData , that.setData , this.data.val三者之间的区别和作用
- .net数据库实现Excel的导入与导出
- git批量恢复所有删除的文件
- 在使用 #import <;objc/message.h>;时 xcode 报 :Too many arguments to function call, expected 0 , have * 解决方法
- php判断是否为时间戳
- 【转载】Gradle构建多模块项目