用两个栈实现队列 c++ 9度题目号1512
2015-10-25 15:23
357 查看
题目:http://ac.jobdu.com/problem.php?pid=1512
思路为用两个栈,一个入队列一个出队列。
对自定义队列MyQueue执行push的时候直接往入队列栈push。
对自定义队列MyQueue执行pop的时候如果出队栈为空而入队栈不为空,就将入队栈中所有元素pop出来push到出队栈中,然后pop一次出队栈。
#include <iostream>
#include <cstdio>
#include <stack>
#define MAXSIZE 100000
using namespace std;
class MyQueue{
private:
stack<int> in, out;
public:
MyQueue() {}
~MyQueue() {}
void push(int key) {
in.push(key);
}
void pop() {
if (out.empty()) { //如果出队栈为空
if (!in.empty()) { //如果入队栈不为空
while (!in.empty()) { //当入队栈不为空
out.push(in.top()); //将入队栈的所有数据转移到出队栈中
in.pop();
}
}
}
if (!out.empty()) { //如果出队栈不为空
cout << out.top() << endl; //输出 出队栈
out.pop();
}
else cout << "-1" << endl;
}
void clear_() {
while (!in.empty()) in.pop();
while (!out.empty()) out.pop();
}
};
int main()
{
MyQueue Q;
int n;
while (cin >> n) {
while (n--) {
string s;
int key;
cin >> s;
if (s == "PUSH") {
cin >> key;
Q.push(key);
}
else if (s == "POP") Q.pop();
}
Q.clear_();
}
return 0;
}
思路为用两个栈,一个入队列一个出队列。
对自定义队列MyQueue执行push的时候直接往入队列栈push。
对自定义队列MyQueue执行pop的时候如果出队栈为空而入队栈不为空,就将入队栈中所有元素pop出来push到出队栈中,然后pop一次出队栈。
#include <iostream>
#include <cstdio>
#include <stack>
#define MAXSIZE 100000
using namespace std;
class MyQueue{
private:
stack<int> in, out;
public:
MyQueue() {}
~MyQueue() {}
void push(int key) {
in.push(key);
}
void pop() {
if (out.empty()) { //如果出队栈为空
if (!in.empty()) { //如果入队栈不为空
while (!in.empty()) { //当入队栈不为空
out.push(in.top()); //将入队栈的所有数据转移到出队栈中
in.pop();
}
}
}
if (!out.empty()) { //如果出队栈不为空
cout << out.top() << endl; //输出 出队栈
out.pop();
}
else cout << "-1" << endl;
}
void clear_() {
while (!in.empty()) in.pop();
while (!out.empty()) out.pop();
}
};
int main()
{
MyQueue Q;
int n;
while (cin >> n) {
while (n--) {
string s;
int key;
cin >> s;
if (s == "PUSH") {
cin >> key;
Q.push(key);
}
else if (s == "POP") Q.pop();
}
Q.clear_();
}
return 0;
}
相关文章推荐
- C/C++专项练习 (四)
- [C++] Lvalue and Rvalue Reference
- 通过重载new与delete运算符避免向系统重复申请内存从而提高程序运行效率的办法
- 预编译头文件来自编译器的早期版本,或者预编译头为 C++ 而在 C 中使用它(或相反)
- 有趣的C语言小程序
- * &
- 关于c语言指针的学习总结1
- 找到数组中重复的和丢失的元素
- C语言<四> 函数与程序结构
- 有效的括号序列(LintCode)
- Heap(堆)学习——C语言描述
- 【转】C语言编程中static变量详解
- C++primer学习:重载运算(1)
- C/C++专项练习 (三)
- C/C++专项练习 (二)
- 使用 Android NDK 的交叉编译工具链移植 C/C++ 项目到安卓平台
- C++STL学习(10)STL算法(1)
- c语言之野指针理解
- 【C语言】 提取子字符串
- 字符串除去空格