用两个栈实现队列 + 用两个队列实现栈

一、用两个栈实现队列:

class CQueue {
    private Stack<Integer> s1;
    private Stack<Integer> s2;


    public CQueue() {
        s1 = new Stack();
        s2 = new Stack();
    }
    //入队列,都进入栈S1
    public void appendTail(int value) {
        s1.push(value);
    }
    //出队列,把S1都推入S2,再取出第一个
    public int deleteHead() {
        if (s2.isEmpty()){
            while(!s1.isEmpty()) {
                s2.push(s1.pop());
            }
        }
        return s2.isEmpty() ? -1 : s2.pop();
    }
}


/**
 * Your CQueue object will be instantiated and called as such:
 * CQueue obj = new CQueue();
 * obj.appendTail(value);
 * int param_2 = obj.deleteHead();
 */

二、用两个队列实现栈

import java.io.IOException;
import java.util.*;
/**
两个队列形成栈
 */
class MyStack {
    Queue<Integer> a;
    Queue<Integer> b;
    /** Initialize your data structure here. */
    public MyStack() {
        a = new LinkedList<>();
        b = new LinkedList<>();
    }
    
     //保证一个队列为空,插入空队列再将另一个队列中数据插入此队列
    public void push(int x) {
        a.offer(x);
        while(!b.isEmpty()){
            a.offer(b.poll());
        }
        Queue temp = a;
        a = b;
        b = temp;
    }
    
    //出栈,即将存有数据的非空队列输出一个数据
    public int pop() {
        return b.poll();
    }
    
    //获取栈顶元素,即获取存有数据的队列的队首数据且不删除
    public int top() {
        return b.peek();
    }
    
    //查看栈是否为空
    public boolean empty() {
        return b.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、付费专栏及课程。

余额充值