算法-数据结构之栈(Java)

最近在看左神的算法课,理解之后在此将代码记录下来
将数组转换成栈:

class ArrayToStack {
    private Integer[] arr;//数据栈
    private Integer index;//索引位

    public ArrayToStack(int initSize) {
        if (initSize < 0) {
            throw new ArrayIndexOutOfBoundsException("参数不能小于0");
        }
        arr = new Integer[initSize];
        index = 0;
    }

    public void push(int num) {
        if (index == arr.length) {
            throw new ArrayIndexOutOfBoundsException();
        }
        arr[index++] = num;
    }

    public Integer pop() {
        if (index <= 0) {
            throw new ArrayIndexOutOfBoundsException();
        }
        return arr[--index];
    }
}

问题一:

如何仅用队列结构实现栈结构?

//两个队列实现一个栈
class TwoQueueStack{
    private Queue<Integer> dataQueue;
    private Queue<Integer> helpQueue;

    public TwoQueueStack(){
        dataQueue = new LinkedList<>();
        helpQueue = new LinkedList<>();
    }

    public void push(int item){
        dataQueue.add(item);
    }

    public Integer pop(){
        if(dataQueue.isEmpty()){
            throw new RuntimeException("栈为空");
        }
        while (dataQueue.size() > 1){
            helpQueue.add(dataQueue.poll());
        }
        int num = dataQueue.poll();
        swap();
        return num;
    }

    public Integer peek(){
        while (dataQueue.size() > 1){
            helpQueue.add(dataQueue.poll());
        }
        int num = dataQueue.peek();
        helpQueue.add(num);
        swap();
        return num;
    }

    private void swap(){
        Queue<Integer> temp = helpQueue;
        helpQueue = dataQueue;
        dataQueue = temp;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值