脱裤子放屁之用两个栈实现队列、用两个队列实现栈

牛客网上有一道很nt的题目,用两个栈实现队列,你直接用队列不好吗?还耗内存,真的是脱裤子放屁,但是骂归骂,题目还是要做的。

用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。

我们可以用stack1进栈,stack2出栈。这样就可以让先进先出的顺序变成先进后出。如果stack2为空的话,stack1进栈元素进stack2 。stack2再出栈就可以了

import java.util.Stack;

public class Solution {
    Stack<Integer> stack1 = new Stack<Integer>();
    Stack<Integer> stack2 = new Stack<Integer>();
    
    public void push(int node) {
        //放就往栈1里面放
        stack1.push(node);
    }
    
    public int pop() {
        //拿就从栈2拿,如果没有就栈1 的入栈
        if(!stack2.isEmpty()){
            return stack2.pop();
        }else{
            while(!stack1.isEmpty()){
                stack2.push(stack1.pop());
            }
            return stack2.pop();
        }
    }
}

我记得还有一道也是nt的题目,用两个队列实现一个栈
我都无语了,吃饱了没事干吗?
在这里插入图片描述
思路就是:放元素的时候,往空的哪一个队列放,放完之后,让另外一个队列的元素进队。每次都这样操作

class MyStack {
    
    Queue<Integer> q1,q2;

    /** Initialize your data structure here. */
    public MyStack() {
        q1 = new LinkedList<>();
        q2 = new LinkedList<>();
    }
    
    /** Push element x onto stack. */
    public void push(int x) {
        if(q1.isEmpty()){
            q1.offer(x);
        }else{
            //往q2里放
            q2.offer(x);
            //吧q1的放到q2去
            while(!q1.isEmpty()){
                q2.offer(q1.poll());
            }
            //现在q1已经没了
            //缓过来,让q2为空
            Queue temp = q1;
            q1 = q2;
            q2 = temp;
            
        }
    }
    
    /** Removes the element on top of the stack and returns that element. */
    public int pop() {
        return q1.poll();
    }
    
    /** Get the top element. */
    public int top() {
        return q1.peek();
    }
    
    /** Returns whether the stack is empty. */
    public boolean empty() {
        return q1.isEmpty();
    }
}

/**
 * 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();
 * boolean param_4 = obj.empty();
 */
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值