232. Implement Queue using Stacks

来源:互联网 发布:淘宝的吉他会是正品吗 编辑:程序博客网 时间:2024/06/03 09:39

题目:

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 toppeek/pop from topsize, and is emptyoperations 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).
思路:

本题采用deque的数据结构,思路与以前的博客Implement Stack using queues一样

代码:

class MyQueue {public:    /** Initialize your data structure here. */    MyQueue() {            }    deque<int> opt;    /** Push element x to the back of queue. */    void push(int x) {        opt.push_back(x);            }        /** Removes the element from in front of queue and returns that element. */    int pop() {        int temp = opt.front();        opt.pop_front();        return temp;            }        /** Get the front element. */    int peek() {        return opt.front();            }        /** Returns whether the queue is empty. */    bool empty() {        return opt.empty();            }};/** * Your MyQueue object will be instantiated and called as such: * MyQueue obj = new MyQueue(); * obj.push(x); * int param_2 = obj.pop(); * int param_3 = obj.peek(); * bool param_4 = obj.empty(); */


原创粉丝点击