leetcode:232 Implement Queue using Stacks-每日編程第十六題

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;
};


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章