The sword refers to Offer_Programming questions_5

Topic 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.
 
class Solution
{
public:
    void push(int node) {
        if(stack1.empty()) {
            stack1.push(node);
        } else {
            while(!stack1.empty()) {
                int val = stack1.top();
                stack1.pop();
                stack2.push(val);
            }
            stack1.push(node);
            while(!stack2.empty()) {
                int val = stack2.top();
                stack2.pop();
                stack1.push(val);
            }
        }
    }

    int pop() {
        int val = stack1.top();
        stack1.pop();
        return val;
    }

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

  

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324642516&siteId=291194637