[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;
}
本文介绍了一种使用两个栈来实现队列的方法。通过这种方式,可以在不需要额外数据结构的情况下实现队列的基本操作:push、pop、peek 和 empty。文章提供了 C++ 的实现代码,并展示了如何在两个栈之间转移元素以实现先进先出的行为。
323

被折叠的 条评论
为什么被折叠?



