class MyStack {
queue<int> qu;
public:
/** Initialize your data structure here. */
MyStack() {
}
/** Push element x onto stack. */
void push(int x) {
qu.push(x);
for(int i=0;i<qu.size()-1;i++)
{
qu.push(qu.front());
qu.pop();
}
}
/** Removes the element on top of the stack and returns that element. */
int pop() {
int val=qu.front();
qu.pop();
return val;
}
/** Get the top element. */
int top() {
return qu.front();
}
/** Returns whether the stack is empty. */
bool empty() {
return qu.empty();
}
};
class MyStack {
queue<int> pushqu;
queue<int> popqu;
int topvalue;
public:
/** Initialize your data structure here. */
MyStack() {
}
/** Push element x onto stack. */
void push(int x) {
pushqu.push(x);
topvalue=x;
}
/** Removes the element on top of the stack and returns that element. */
int pop() {
while(pushqu.size()>1)
{
topvalue=pushqu.front();
popqu.push(topvalue);
pushqu.pop();
}
int result=pushqu.front();
pushqu.pop();
queue<int> temp=pushqu;
pushqu=popqu;
popqu=temp;
return result;
}
/** Get the top element. */
int top() {
return topvalue;
}
/** Returns whether the stack is empty. */
bool empty() {
return pushqu.empty();
}
};
C++用一个队列实现栈push:先把元素放到栈中,然后将元素中的size-1个元素插入到队列的尾部。top:由于push操作已经将队列中的元素操作成了先进后出的类型,因此可以直接front取出元素。class MyStack { queue<int> qu;public: /** Initialize your data structure here. */ MyStack() { } /** Push element x onto sta