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

The queue should supportpush(element),pop()andtop()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.

Have you met this question in a real interview?

Yes

Example

push(1)
pop()     // return 1
push(2)
push(3)
top()     // return 2
pop()     // return 2

Challenge

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

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\(\)\) {

        int top = stack2.top\(\);

        stack2.pop\(\);

        return top;

    }



    moveElements\(\);



    if \(!stack2.empty\(\)\) {

        int top = stack2.top\(\);

        stack2.pop\(\);

        return top;

    } else {

        return -1;

    }

}



int top\(\) {

    // write your code here

    if \(!stack2.empty\(\)\) {

        return stack2.top\(\);

    }

    moveElements\(\);

    if \(!stack2.empty\(\)\) {

        return stack2.top\(\);

    } else {

        return -1;

    }

}

private:

void moveElements\(\) {

    while \(!stack1.empty\(\)\) {

        stack2.push\(stack1.top\(\)\);

        stack1.pop\(\);

    }

}

};

results matching ""

    No results matching ""