leetcode-225. 用队列实现栈
使用队列实现栈的下列操作:
1.push(x) -- 元素 x 入栈
void push(int x) {
q.push(x);
}
//压栈是一样的就不用修改了
2.pop() -- 移除栈顶元素
栈的栈顶是最后一个元素,按照栈的规则是FILO(先进后出),而栈的栈顶对于队列来说就是最后一个要出来的。
要移除栈顶元素就要先将队列前面的值全部移走再进去,就完成了POP的操作
int pop() {
int size = q.size()-1;
for(int i=0;i<size;i++)
{
int data = q.front(); //取出口第一个数保存
q.pop(); //取出这个数
q.push(data); //将取出的数放到队列的最后
}
int d = q.front(); //当把所有前面的值都移走了之后,再把第一个元素移除
q.pop();
return d;
}
3.top() -- 获取栈顶元素
int top() {
int size = q.size()-1;
for(int i=0;i<size;i++)
{
int data = q.front();
q.pop();
q.push(data);
}
//和上一步是一样的,不过这次是将栈顶元素也保存下来送回队列里
int d = q.front();
q.pop();
q.push(d); //只是观看栈顶元素,并不需要移除
return d; //返回栈顶元素
}
4.empty() -- 返回栈是否为空
bool empty() {
if(!q.empty()){
return false;
}
else
{
return true;
}
}
完整代码:
class MyStack {
public:
/** Initialize your data structure here. */
queue<int> q;
MyStack() {
}
/** Push element x onto stack. */
void push(int x) {
q.push(x);
}
/** Removes the element on top of the stack and returns that element. */
int pop() {
int size = q.size()-1;
for(int i=0;i<size;i++)
{
int data = q.front();
q.pop();
q.push(data);
}
int d = q.front();
q.pop();
return d;
}
/** Get the top element. */
int top() {
int size = q.size()-1;
for(int i=0;i<size;i++)
{
int data = q.front();
q.pop();
q.push(data);
}
int d = q.front();
q.pop();
q.push(d);
return d;
}
/** Returns whether the stack is empty. */
bool empty() {
if(!q.empty()){
return false;
}
else
{
return true;
}
}
};
/**
* 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();
*/