Implement Stack using Queues
class Stack {
private:
queue<int> q;
public:
// Push element x onto stack.
void push(int x) {
queue<int> t;
while (!q.empty()) {
t.push(q.front());
q.pop();
}
q.push(x);
while(!t.empty()) {
q.push(t.front());
t.pop();
}
}
// Removes the element on top of the stack.
void pop() {
q.pop();
}
// Get the top element.
int top() {
while (!q.empty()) return q.front();
}
// Return whether the stack is empty.
bool empty() {
return q.empty();
}
};
Implement Queue using Stacks
class Queue {
private:
stack<int> s;
public:
// Push element x to the back of queue.
void push(int x) {
stack<int> t;
while (!s.empty()) {
t.push(s.top());
s.pop();
}
s.push(x);
while(!t.empty()) {
s.push(t.top());
t.pop();
}
}
// Removes the element from in front of queue.
void pop(void) {
s.pop();
}
// Get the front element.
int peek(void) {
if (!s.empty()) return s.top();
}
// Return whether the queue is empty.
bool empty(void) {
return s.empty();
}
};
本文详细介绍了如何使用队列实现栈结构,以及如何利用栈来实现队列,包括具体代码实现与原理说明。
1149

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



