problem
225. Implement Stack using Queues
code
class MyStack {
public:
std::queue<int> myqueue;
/** Initialize your data structure here. */
MyStack() {
}
/** Push element x onto stack. */
void push(int x) {
myqueue.push(x);
for(int i=0; i<myqueue.size()-1; i++)
{
myqueue.push(myqueue.front());
myqueue.pop();
}
}
/** Removes the element on top of the stack and returns that element. */
int pop() {
int b = myqueue.front();
myqueue.pop();
return b;
}
/** Get the top element. */
int top() {
return myqueue.front();//
}
/** Returns whether the stack is empty. */
bool empty() {
return myqueue.empty();
}
};
/**
* Your MyStack object will be instantiated and called as such:
* MyStack obj = new MyStack();
* obj.push(x);
* int param_2 = obj.pop();
* int param_3 = obj.top();
* bool param_4 = obj.empty();
*/
View Code
注意,能够理解并熟悉堆栈stack和队列queue的性质,熟练使用stack和queue。堆栈是先进后出,队列是先进先出。
re
1. leetcode_Implement Stack using Queues;
end