admin管理员组

文章数量:1636972

As the title described, you should only use two stacks to implement a queue’s actions.

The queue should support push(element), pop() and top() where pop is pop the first(a.k.a front) element in the queue.

Both pop and top methods should return the value of first element.

Challenge
implement it by two stacks, do not use any other data structure and push, pop and top should be O(1) by AVERAGE.

1.

在push上做文章,每次push前,将stack1中的元素依次弹到stack2,element push到stack2后,再将stack2依次弹到stack1.
这样pop和top的操作就是O(1)。

但push的复杂度比较高

class Queue {
public:
    stack<int> stack1;
    stack<int> stack2;

    Queue() {
        // do intialization if necessary
    }

    void push(int element) {
        // write your code here

        while(!stack1.empty()){
            int top=stack1.top();
            stack1.pop();
            stack2.push(top);
        }

        stack2.push(element);

        while(!stack2.empty()){
            int top=stack2.top();
            stack2.pop();
            stack1.push(top);
        }

    }

    int pop() {
        // write your code here
        int res=stack1.top();
        stack1.pop();
        return res;
    }

    int top() {
        // write your code here
        return stack1.top();
    }
};

2.

push照常;
pop和top这样做:如果stack2不为空,pop stack2;否则将stack1中所有元素弹到stack2;

这样整体时间复杂度较低。

class Queue {
public:
    stack<int> stack1;
    stack<int> stack2;

    Queue() {
        // do intialization if necessary
    }

    void push(int element) {
        // write your code here
        stack1.push(element);
    }

    int pop() {
        // write your code here
        if(stack2.empty()){
            pushInto2(stack1,stack2);
        }
        int res=stack2.top();
        stack2.pop();
        return res;
    }

    int top() {
        // write your code here
        if(stack2.empty()){
            pushInto2(stack1,stack2);
        }

        return stack2.top();
    }

    private:
    void pushInto2(stack<int> &stack1,stack<int> &stack2){
        while(!stack1.empty()){
            stack2.push(stack1.top());
            stack1.pop();
        }
    }

};

本文标签: implementQueueStacks