diff --git a/notes/9. 用两个栈实现队列.md b/notes/9. 用两个栈实现队列.md index 9d67a975..df8dc723 100644 --- a/notes/9. 用两个栈实现队列.md +++ b/notes/9. 用两个栈实现队列.md @@ -2,7 +2,7 @@ ## 题目链接 -[牛客网](https://www.nowcoder.com/practice/54275ddae22f475981afa2244dd448c6?tpId=13&tqId=11158&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking&from=cyc_github) +[Leetcode](https://leetcode.cn/problems/yong-liang-ge-zhan-shi-xian-dui-lie-lcof/) ## 题目描述 @@ -15,21 +15,28 @@ in 栈用来处理入栈(push)操作,out 栈用来处理出栈(pop)操

```java -Stack in = new Stack(); -Stack out = new Stack(); +class CQueue { + private Stack in = new Stack<>(); + private Stack out = new Stack<>(); -public void push(int node) { - in.push(node); -} + public CQueue() { -public int pop() throws Exception { - if (out.isEmpty()) - while (!in.isEmpty()) - out.push(in.pop()); + } - if (out.isEmpty()) - throw new Exception("queue is empty"); + public void appendTail(int value) { + in.push(value); + } - return out.pop(); + public int deleteHead() { + if (out.isEmpty()) { + while (!in.isEmpty()) { + out.push(in.pop()); + } + } + if (out.isEmpty()) { + return -1; + } + return out.pop(); + } } ```