您的位置:首页 > 产品设计 > UI/UE

[LeetCode]232. Implement Queue using Stacks

2017-04-15 20:28 295 查看

[LeetCode]232. Implement Queue using Stacks

题目描述



思路

两个栈实现

代码

#include <iostream>
#include <stack>

using namespace std;

class MyQueue {
public:
/** Initialize your data structure here. */
MyQueue() { }

/** Push element x to the back of queue. */
void push(int x) {
input.push(x);
}

/** Removes the element from in front of queue and returns that element. */
int pop() {
int res = peek();
if (output.size()) {
output.pop();
}
return res;
}

/** Get the front element. */
int peek() {
if (output.empty()) {
while (input.size()) {
output.push(input.top());
input.pop();
}
}
if(output.size())
return output.top();
return 0;
}

/** Returns whether the queue is empty. */
bool empty() {
return input.empty() && output.empty();
}

private:
stack<int> input, output;
};

int main() {
MyQueue obj;

int param_2 = obj.pop();
int param_3 = obj.peek();
bool param_4 = obj.empty();

cout << param_2 << " " << param_3 << " " << param_4 << endl;

system("pause");

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: