Jianzhi 5. Implementing a queue with two stacks

Link

topic

insert image description here

train of thought

pushOperation: Insert the data into the normal stack1operation
pop: It is to stack1import all the data in the middle stack2and then pop up stack2the head, so

  • If it is not empty, the top element of the stack stack2will be popped directlystack2
  • Otherwise, first stack1import the elements of

Simulate it and it will be clear

the code

class Solution {
    
    
public:
    void push(int node) {
    
    
        stack1.push(node);
    }
    int pop() {
    
    
        int ret;
        if (stack2.empty()) {
    
    
            while (!stack1.empty()) {
    
    
                stack2.push(stack1.top());
                stack1.pop();
            }
            ret = stack2.top();
            stack2.pop();
        } else {
    
    
            ret = stack2.top();
            stack2.pop();
        }
        return ret;
    }
private:
    stack<int> stack1;
    stack<int> stack2;
};

other

Likou also uses queues to implement stacks, and it is best to write them in C.

Guess you like

Origin blog.csdn.net/weixin_44119881/article/details/112238160