首页 > 其他 > 详细

leetcode 225 Implement Stack using Queues

时间:2015-06-20 11:57:57      阅读:524      评论:0      收藏:0      [点我收藏+]

1. 问题描述

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

  • push(x) 将元素x入栈。
  • pop() 出栈。
  • top() 获取栈顶元素。
  • empty() 判断是否为空。

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


2 方法和思路

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

  • 入栈时将元素都存入q1队列中。
  • 出栈时将q1中前n-1个元素放入q2队列,然后pop出q1的最后一个元素,最后将q2队列中的元素在放回到q1中。
  • 获取栈顶元素思路类似,只不过q1最后一个元素返回后,将其入q2,然后再将q2中所有元素放回到q1队列中,恢复原样。
  • 判断栈是否为空直接判断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

原文:http://blog.csdn.net/jeanphorn/article/details/46572309

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!