[Daily question] 25: Using the queue to implement the stack

Title description:

Use the queue to implement the following operations of the stack:

  • push (x) – push element x onto the stack
  • pop () – remove the top element of the stack
  • top ()-get the top element of the stack
  • empty () – returns whether the stack is empty

note:

You can only use the basic operations of the queue-that is, push to back, peek / pop from front, size, and is empty operations are legal.
Your language may not support queues. You can use list or deque (double-ended queue) to simulate a queue, as long as it is a standard queue operation.
You can assume that all operations are valid (for example, pop or top operations are not called on an empty stack).

Answer code:

class MyStack {
    queue<int> q1;
public:
    /** Initialize your data structure here. */
    MyStack() {

    }
    
    /** Push element x onto stack. */
    void push(int x) {
        q1.push(x);
    }
    
    /** Removes the element on top of the stack and returns that element. */
    //力扣模版需要返回值进行检测
    //int pop() {
    void pop(){
        queue<int> q2;
        while (q1.size() > 1)
		{
			q2.push(q1.front());
			q1.pop();
		}
        //int tmp = q1.front();
        q1.pop();
		q1 = q2;
        //return tmp;
    }
    
    /** Get the top element. */
    int top() {
        queue<int> q2;
        while (q1.size() > 1)
		{
			q2.push(q1.front());
			q1.pop();
		}
        int tmp = q1.front();
        q2.push(q1.front());
        q1 = q2;
        return tmp;
    }
    
    /** Returns whether the stack is empty. */
    bool empty() {
        return q1.empty();
    }
};

If you have different opinions, please leave a message to visit! ! !

Published 152 original articles · praised 45 · 10,000+ views

Guess you like

Origin blog.csdn.net/AngelDg/article/details/105370983