mirror of
https://github.com/CyC2018/Interview-Notebook.git
synced 2026-10-30 18:23:52 +00:00
Update 9. 用两个栈实现队列.md
题目链接改为力扣中的对应题目,题目描述和代码按该题的接口调整。
This commit is contained in:
+20
-13
@@ -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)操
|
||||
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/3ea280b5-be7d-471b-ac76-ff020384357c.gif" width="450"/> </div><br>
|
||||
|
||||
```java
|
||||
Stack<Integer> in = new Stack<Integer>();
|
||||
Stack<Integer> out = new Stack<Integer>();
|
||||
class CQueue {
|
||||
private Stack<Integer> in = new Stack<>();
|
||||
private Stack<Integer> 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();
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Reference in New Issue
Block a user