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

题目链接

检讨代码TAT,模拟思路

    Stack<Integer> s1 = new Stack<>();
    Stack<Integer> s2 = new Stack<>();
    public CQueue() {
        s1 = new Stack<>();
        s2 = new Stack<>();
    }

    // 加入尾部
    public void appendTail(int value) {
        if (s1.isEmpty() && s2.isEmpty()) {
            s1.add(value);
        } else if (s2.isEmpty()) {
            s1.add(value);
        } else {
            s2.add(value);
        }
    }

    // 加入首部
    public int deleteHead() {
        if (s1.isEmpty() && s2.isEmpty()) return -1;

        // 此时需要将s1的元素全部,压入s2,取得首部元素,再将s2中元素压入回s1,不破坏原来的顺序
        if (s2.isEmpty()) {
            while (!s1.isEmpty() && s1.size() > 1) {
                s2.add(s1.pop());
            }
            // 取得s1首部的元素
            int temp = s1.pop();

            // 将s2中的元素再放入回s1
            while (!s2.isEmpty()) {
                s1.add(s2.pop());
            }
            return temp;
        } else {
            while (!s2.isEmpty() && s2.size() > 1) {
                s1.add(s2.pop());
            }
            int temp = s2.pop();

            // 将s2中的元素再放入回s1
            while (!s1.isEmpty()) {
                s2.add(s1.pop());
            }
            return temp;
        }
    }

优质代码,来自

class CQueue {
    LinkedList<Integer> A, B;
    public CQueue() {
        A = new LinkedList<Integer>();
        B = new LinkedList<Integer>();
    }
    public void appendTail(int value) {
        A.addLast(value);
    }
    public int deleteHead() {
        if(!B.isEmpty()) return B.removeLast();
        if(A.isEmpty()) return -1;
        while(!A.isEmpty())
            B.addLast(A.removeLast());
        return B.removeLast();
    }
}

作者:jyd
链接:https://leetcode-cn.com/problems/yong-liang-ge-zhan-shi-xian-dui-lie-lcof/solution/mian-shi-ti-09-yong-liang-ge-zhan-shi-xian-dui-l-2/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
posted @ 2020-11-22 09:25  Bears9  阅读(76)  评论(0编辑  收藏  举报