Brushing notes (four)-using the stack to achieve the queue

Brushing notes (four)-using the stack to achieve the queue

Title description

Use two stacks to implement a queue to complete the Push and Pop operations of the queue. The elements in the queue are of type int.

Idea: one stack stack1 as push, push the elements of the queue into the stack; another stack stack2 as pop, when the team is not empty, then directly pop the elements in the stack, if it is empty , You need to pop the elements in stack1 one by one, and then push to stack2.

class Solution
{
public:
    void push(int node) {
        stack1.push(node);
    }

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

private:
    stack<int> stack1;
    stack<int> stack2;
};

 

Published 36 original articles · 19 praises · 20,000+ views

Guess you like

Origin blog.csdn.net/GJ_007/article/details/105396853