leetcode:232 Implement Queue using Stacks-每日编程第十六题

来源:互联网 发布:那个软件看欧美剧 编辑:程序博客网 时间:2024/05/20 20:58

Implement Queue using Stacks

Total Accepted: 26279 Total Submissions: 77749 Difficulty: Easy

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 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).
这题是我今年腾讯二面的一道算法题。题目只有一句话:用实现一个队列。
思路:
1).尽可能让时间度,复杂度降低。
2).通过递归,使得每个插入的新元素,都插入到栈底。复杂度为o(n)。
3).因此删除,弹出的复杂度都为o(1)。
4).empty()直接用调用栈的empty()就可以了。

class Queue {public:    // Push element x to the back of queue.    void push(int x) {        if(sta.empty()){            sta.push(x);        }else{            int tem = sta.top();            sta.pop();            push(x);            sta.push(tem);        }    }    // Removes the element from in front of queue.    void pop(void) {        if(!sta.empty()){            sta.pop();        }    }    // Get the front element.    int peek(void) {        if(!sta.empty()){            int tem = sta.top();            return tem;        }else{            return -1;        }    }    // Return whether the queue is empty.    bool empty(void) {        return sta.empty();    }private:    stack<int> sta;};


0 0