如何用栈实现队列以及用队列实现栈

用栈实现队列
用两个栈实现队列
算法思路

1.入队列:将元素放置到s1中
2.出队列:检测s2是否为空,若为空,将s1中的元素搬移到s2中,删除s2栈顶的元素;若不为空,则删除s2栈顶的元素
3.获取队头元素:检测s2是否为空,若为空,将s1中元素搬移到s2中;若不为空,则从s2栈顶直接获取
4.检测队列是否为空:若两个栈都为空,则队列为空

Java代码

class MyQueue {
    private Stack<Integer> s1;//模拟入队列
    private Stack<Integer> s2;//模拟出队列

    /** Initialize your data structure here. */
    public MyQueue() {
        s1 = new Stack<>();
        s2 = new Stack<>();
    }
    
    /** Push element x to the back of queue. */
    public void push(int x) {
        s1.push(x);
    }
    
    /** Removes the element from in front of queue and returns that element. */
    public int pop() {
        if(s2.isEmpty()){
            while(!s1.isEmpty()){
                s2.push(s1.pop());
            }  
        }
        return s2.pop();
    }
    
    /** Get the front element. */
    public int peek() {
        if(s2.isEmpty()){
            while(!s1.isEmpty()){
                s2.push(s1.pop());
            }
        }
        return s2.peek();
    }
    
    /** Returns whether the queue is empty. */
    public boolean empty() {
        return s1.isEmpty() && s2.isEmpty();
    }
}

用队列实现栈

算法思路

1.入栈:将元素入队列到q1中
2.出栈:
①将q1中元素移动到q2中
②将q1中剩余的一个元素删除掉
③交换q1和q2
3.获取栈顶元素:
①将q1中元素移动到q2中
②从q1中取栈顶元素
③将q1中的一个元素搬移到q2中
④交换q1和q2
4.判空:q1为空

Java代码

class MyStack {
    private Queue<Integer> q1;
    private Queue<Integer> q2;

    /** Initialize your data structure here. */
    public MyStack() {
        q1 = new LinkedList<>();
        q2 = new LinkedList<>();
    }
    
    /** Push element x onto stack. */
    public void push(int x) {
        q1.offer(x);
    }
    
    /** Removes the element on top of the stack and returns that element. */
    public int pop() {
        //将q1中size-1个元素搬移到q2中
        while(q1.size() > 1){
            q2.offer(q1.poll());
        }
        //删除q1中的队头元素
        int ret = q1.poll();
        Queue<Integer> temp = q1;
        q1 = q2;
        q2 = temp;
        return ret;
    }
    
    /** Get the top element. */
    public int top() {
        //将q1中size-1个元素搬移到q2中
        while(q1.size() > 1){
            q2.offer(q1.poll());
        }
        int ret = q1.peek();
        q2.offer(q1.poll());
        Queue<Integer> temp = q1;
        q1 = q2;
        q2 = temp;
        return ret;
    }
    
    /** Returns whether the stack is empty. */
    public boolean empty() {
        return q1.isEmpty();
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值