C++面试笔试必知必会-栈实现队列队列实现栈


一、用栈实现队列(力扣232题)

在这里插入图片描述
class MyQueue {
public:
MyQueue() {

}

void push(int x) {
    s1.push (x);
}

int pop() {
    if(s2.empty())
    {
        while(!s1.empty())
        {
            s2.push(s1.top());
            s1.pop();
        }
    }
    int val=s2.top();    
    s2.pop();
    return val;
}

int peek() {
    if(s2.empty())
    {
        while(!s1.empty())
    {
        s2.push(s1.top());
        s1.pop();
    }
    }
    return s2.top();    
}

bool empty() {
    return s1.empty()&&s2.empty();
}
    stack<int> s1;
    stack<int> s2;

};

/**

  • Your MyQueue object will be instantiated and called as such:
  • MyQueue* obj = new MyQueue();
  • obj->push(x);
  • int param_2 = obj->pop();
  • int param_3 = obj->peek();
  • bool param_4 = obj->empty();
    */

二、用队列实现栈(力扣225题)

在这里插入图片描述

class MyStack {
    
    
public:
    MyStack() {
    
    

    }
    
    void push(int x) {
    
    
        q2.push(x);
        while(!q1.empty())
        {
    
    
            q2.push(q1.front());
            q1.pop();
        }
        swap(q1,q2);
    }
    
    int pop() {
    
    
        int val=q1.front();
        q1.pop();
        return val;
    }
    
    int top() {
    
    
        return q1.front();
    }
    
    bool empty() {
    
    
        return q1.empty();
    }
    queue<int> q1;
    queue<int> q2;
};

/**
 * Your MyStack object will be instantiated and called as such:
 * MyStack* obj = new MyStack();
 * obj->push(x);
 * int param_2 = obj->pop();
 * int param_3 = obj->top();
 * bool param_4 = obj->empty();
 */

猜你喜欢

转载自blog.csdn.net/Abieai/article/details/124070074