美文网首页
用两个栈实现队列

用两个栈实现队列

作者: 上杉丶零 | 来源:发表于2019-09-21 20:43 被阅读0次
    package leetcode.剑指Offer.用两个栈实现队列;
    
    import java.util.Stack;
    
    public class LeetCode {
        public static void main(String[] args) {
        }
    }
    
    class CQueue {
        Stack<Integer> stack1 = new Stack<>();
        Stack<Integer> stack2 = new Stack<>();
    
        public CQueue() {}
    
        public void appendTail(int value) {
            stack1.push(value);
        }
    
        public int deleteHead() {
            if (stack1.isEmpty() && stack2.isEmpty()) {
                return -1;
            }
    
            if (stack2.isEmpty()) {
                while (!stack1.isEmpty()) {
                    stack2.push(stack1.pop());
                }
            }
    
            return stack2.pop();
        }
    }
    
    image.png

    相关文章

      网友评论

          本文标题:用两个栈实现队列

          本文链接:https://www.haomeiwen.com/subject/mtweuctx.html