代码随想录算法训练营day10| 232. 用栈实现队列,225. 用队列实现栈

232. 用栈实现队列

232. 用栈实现队列

讲解 

 输出栈如果为空,就把进栈数据全部导入进来,再从出栈弹出数据,如果输出栈不为空,则直接从出栈弹出数据。

class MyQueue {
public:
    stack<int> st1;
    stack<int> st2;
    MyQueue() {

    }
    
    void push(int x) {
        st1.push(x);
    }
    
    int pop() {
        if(!st2.empty()) {
            int ans = st2.top();
            st2.pop();
            return ans;
        }
        while(!st1.empty()){
            st2.push(st1.top());
            st1.pop();
        }
        int ans1 = st2.top();
        st2.pop();
        return ans1;

    }
    
    int peek() {
        int ans = this->pop();
        st2.push(ans);
        return ans;
    }
    
    bool empty() {
        return st1.empty() && st2.empty();
    }
};

/**
 * 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. 用队列实现栈

225. 用队列实现栈

class MyStack {
public:
    //queue2始终为空
    queue<int> queue1;
    queue<int> queue2;
    MyStack() {

    }
    
    void push(int x) {
        queue2.push(x);
        while(!queue1.empty()){
        
            queue2.push(queue1.front());
            queue1.pop();
            
        }
        //不用swap
        queue1 = queue2;            // 再将que2赋值给que1
        while (!queue2.empty()) { // 清空que2
            queue2.pop();
        }

    }
    
    int pop() {
        int ans = queue1.front();
        queue1.pop();
        return ans;
    }
    
    int top() {
        return queue1.front();
    }
    
    bool empty() {
        return queue1.empty();
    }
};

/**
 * 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();
 */

class MyStack {
public:
	queue<int> q1;
	queue<int> q2;

    MyStack() {

    }
    
    void push(int x) {
		q1.push(x);
    }
    
    int pop() {
		int size = q1.size()-1;
		while(size--){
			q2.push(q1.front());
			q1.pop();
		}
		int ans = q1.front();
		q1.pop();
		while(!q2.empty()){
			q1.push(q2.front());
			q2.pop();
		}
		return ans;
    }
    
    int top() {
		int ans = this->pop();
		q1.push(ans);
		return ans;
    }
    
    bool empty() {
		return q1.empty();
    }
};

/**
 * 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();
 */

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值