0
点赞
收藏
分享

微信扫一扫

剑指offer刷题(栈,队列)

爱读书的歌者 2022-02-26 阅读 81

剑指offer刷题(栈,队列)

image-20220226174642185

常规做法:使用stack完成两个栈的压入和弹出

class CQueue {
        Stack<Integer> stack1 ;
        Stack<Integer> stack2 ;

    public CQueue() {
        stack1 = new Stack<Integer>();
        stack2 = new Stack<Integer>();
    }
    
    public void appendTail(int value) {
        stack1.push(value);
    }
    
    public int deleteHead() {
        if (!stack2.empty()){
            return stack2.pop();
        }
        if (!stack1.empty()) {
            while (!stack1.empty()) {
                stack2.push(stack1.pop());
            }
        }
        return stack2.empty() ? -1 : stack2.pop();
    }
    
}

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

image-20220226174836458

但是底层stack继承了vector效率不高因为需要考虑其中扩容的问题,所以我们使用Linked List

因为Linked List底层继承了deque队列

image-20220226175905435

image-20220226175933483

所以我们可以使用4种方式进行弹出处理

代码如下

class CQueue {
        LinkedList<Integer> linkedList1;
        LinkedList<Integer> linkedList2;

    public CQueue() {
        linkedList1 = new LinkedList();
        linkedList2 = new LinkedList();
    }
    
    public void appendTail(int value) {
        linkedList1.add(value);
    }
    
    public int deleteHead() {
        if (!linkedList2.isEmpty()){
            return linkedList2.remove();
        }
        if (!linkedList1.isEmpty()) {
            while (!linkedList1.isEmpty()) {
                linkedList2.add(linkedList1.remove());
            }
        }
        return linkedList2.isEmpty() ? -1 : linkedList2.remove();
    }
    
}

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

image-20220226180503463

举报

相关推荐

0 条评论