leetcode 225 Implement Stack using Queues

1. 问题描述

  用队列来模拟栈的操作。实现如下栈操作:   

  注意:只能用队列的标准操作,队头取元素,队尾插入元素,获取队列的大小,以及队列是否为空。

2 方法和思路

  可以用两个队列q1和q2来实现栈的操作,设q2为辅助队列。   

判断栈是否为空直接判断q1队列是否为空即可。

  C++代码如下:   

class Stack {private:queue<int> q1;queue<int> q2;public:// Push element x onto stack.void push(int x) {q1.push(x);}// Removes the element on top of the stack.void pop() {int n = q1.size();for(int i = 0; i < n -1; i++){q2.push(q1.front());q1.pop();}q1.pop();while(!q2.empty()){q1.push(q2.front());q2.pop();}}// Get the top element.int top() {int re,n = q1.size();for(int i = 0; i < n -1; i++){q2.push(q1.front());q1.pop();}re = q1.front();q2.push(q1.front());q1.pop();while(!q2.empty()){q1.push(q2.front());q2.pop();}return re;}// Return whether the stack is empty.bool empty() {return q1.empty();}};

,你有没有这样的感觉,坐在一列火车上,

leetcode 225 Implement Stack using Queues

相关文章:

你感兴趣的文章:

标签云: