题意:用堆栈模拟队列。
思路:简单模拟。
class Queue {
public:
stack<int> s;
// Push element x to the back of queue.
void push(int x) {
s.push(x);
}
// Removes the element from in front of queue.
void pop(void) {
stack<int> temps;
while(!s.empty()) {
temps.push(s.top());
s.pop();
}
temps.pop();
while(!temps.empty()) {
s.push(temps.top());
temps.pop();
}
}
// Get the front element.
int peek(void) {
stack<int> temps;
int re;
while(!s.empty()) {
temps.push(s.top());
s.pop();
}
re = temps.top();
//temps.pop();
while(!temps.empty()) {
s.push(temps.top());
temps.pop();
}
return re;
}
// Return whether the queue is empty.
bool empty(void) {
return s.empty();
}
};

本文介绍了一种使用堆栈来模拟队列操作的方法。通过两个堆栈的辅助转换,实现了队列的基本功能,包括入队(push)、出队(pop)、查看队首元素(peek)及判断队列是否为空(empty)。
274

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



