LeetCode链接: link.
解题思路:
不管底层用什么结构实现,永远保证数据先进后出的一个逻辑数据结构,即栈
借助队列实现栈,可以使用两个队列,也可以只是用一个队列,本解只借助一个队列即可
入栈,即把数据进行入队,为了保证栈的特性先进后出,因此需要在push方法中对入队之前的所有元素进行一次出 队入队操作,以保证所有数据达到先进后出的顺序
出栈,由于队列数据顺序已经调整,所以只需取队头元素即可
class MyStack {
public:
/** Initialize your data structure here. */
MyStack() {
}
/** Push element x onto stack. */
void push(int x) {
int size = q.size();
q.push(x);
while(size--)
{
int temp = q.front();
q.pop();
q.push(temp);
}
}
/** Removes the element on top of the stack and returns that element. */
int pop() {
int popVal = q.front();
q.pop();
return popVal;
}
/** Get the top element. */
int top() {
return q.front();
}
/** Returns whether the stack is empty. */
bool empty() {
return q.empty();
}
private:
queue<int> q;
};