码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode232:Implement Queue using Stacks

时间:2015-07-10 23:44:01      阅读:153      评论:0      收藏:0      [点我收藏+]

标签:

Implement the following operations of a queue using stacks.

  • push(x) – Push element x to the back of queue.
  • pop() – Removes the element from in front of queue.
  • peek() – Get the front element.
  • empty() – Return whether the queue is empty.

Notes:

  • You must use only standard operations of a stack – which means only
    push to top, peek/pop from top, size, and is empty operations are
    valid.
  • Depending on your language, stack may not be supported natively. You
    may simulate a stack by using a list or deque (double-ended queue),
    as long as you use only standard operations of a stack.
  • You may assume that all operations are valid (for example, no pop or
    peek operations will be called on an empty queue).

使用栈来实现一个队列,这个题目之前在《剑指offer》上面见过,没有什么好说的。使用两个栈,一个栈用来保存插入的元素,另外一个栈用来执行pop或top操作,每当执行pop或top操作时检查另外一个栈是否为空,如果为空,将第一栈中的元素全部弹出并插入到第二个栈中,再将第二个栈中的元素弹出即可。需要注意的是这道题的编程时有一个技巧,可以使用peek来实现pop,这样可以减少重复代码。编程时要能扩展思维,如果由于pop函数的声明再前面就陷入用pop来实现peek的功能的话就会感觉无从下手了。

runtime:0ms

class Queue {
public:
    // Push element x to the back of queue.
    void push(int x) {
        pushStack.push(x);
    }

    // Removes the element from in front of queue.
    void pop(void) {
        peek();//这里可以使用peek进行两个栈之间元素的转移从而避免重复代码
        popStack.pop();
    }

    // Get the front element.
    int peek(void) {
        if(popStack.empty())
        {
            while(!pushStack.empty())
            {
                popStack.push(pushStack.top());
                pushStack.pop();
            }
        }
        return popStack.top();
    }

    // Return whether the queue is empty.
    bool empty(void) {
        return pushStack.empty()&&popStack.empty();
    }

    private:
    stack<int> pushStack;//数据被插入到这个栈中
    stack<int> popStack;//数据从这个栈中弹出
};

版权声明:本文为博主原创文章,未经博主允许不得转载。

LeetCode232:Implement Queue using Stacks

标签:

原文地址:http://blog.csdn.net/u012501459/article/details/46836073

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!