关闭

LeetCode232:Implement Queue using Stacks

969人阅读 评论(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;//数据从这个栈中弹出
};
0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:335108次
    • 积分:6175
    • 等级:
    • 排名:第4161名
    • 原创:261篇
    • 转载:43篇
    • 译文:13篇
    • 评论:43条
    友情链接
    博客专栏
    文章分类
    最新评论