由两个栈组成的队列

文章介绍了如何使用两个栈来实现队列的功能,包括push、pop、peek和empty操作。在LeetCode的题目中,当pop和peek时,如果head为空,则需要将tail的所有元素转移到head。而在优化后的剑指Offer解法中,对于deleteHead操作,增加了当头栈和尾栈都为空时返回-1的情况。
摘要由CSDN通过智能技术生成

leetcode链接:
232. 用栈实现队列

class MyQueue {

    private Stack<Integer> head;
    private Stack<Integer> tail;

    public MyQueue() {
        head = new Stack<Integer>();
        tail = new Stack<Integer>();
    }
    
    public void push(int x) {
        //push的时候将元素push到队尾tail
        tail.push(x);
    }
    
    public int pop() {
        //pop的时候注意:当head有元素时,直接pop队头head中的元素即可;否则,将tail依次push到head中,再弹出head中的元素
        if(head.isEmpty()){
            while(!tail.isEmpty()){
                head.push(tail.pop());
            }
        }

        return head.pop();
    }
    
    public int peek() {
        //peek的时候同pop一样,如果队头head中有元素,直接返回head中的元素即可;否则将tail依次push到head中,再返回head中的元素
        if(head.isEmpty()){
            while(!tail.isEmpty()){
                head.push(tail.pop());
            }
        }
        return head.peek();
    }
    
    public boolean empty() {
        return tail.isEmpty() && head.isEmpty();
    }
}

/**
 * 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();
 * boolean param_4 = obj.empty();
 */

剑指 Offer 09. 用两个栈实现队列

class CQueue {

    private Stack<Integer> head;
    private Stack<Integer> tail;

    public CQueue() {
        head = new Stack<Integer>();
        tail = new Stack<Integer>();
    }
    
    public void appendTail(int value) {
        tail.push(value);
    }
    
    public int deleteHead() {
        int result;
        //比上面增加了一种情况
        if(head.isEmpty() && tail.isEmpty()){
            result = -1;
        }else if(head.isEmpty()){
            while(!tail.isEmpty()){
                head.push(tail.pop());
            }
            result = head.pop();
        }else{
            result = head.pop();
        }
        return result;
    }
}

/**
 * Your CQueue object will be instantiated and called as such:
 * CQueue obj = new CQueue();
 * obj.appendTail(value);
 * int param_2 = obj.deleteHead();
 */
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值