~~~
import java.util.Stack;
/**
* 用兩個棧實現隊列
*/
public class Algorithm01 {
public static void main(String arg[]) {
StackQueue queue = new StackQueue();
queue.add(10);
queue.add(12);
queue.add(1);
queue.add(3);
Integer result = null;
while ((result = queue.poll()) != null) {
System.out.println(result);
}
}
}
// 用棧實現隊列
class StackQueue {
private Stack<Integer> pushStack = new Stack<>();
private Stack<Integer> popStack = new Stack<>();
private void pushToPopStack() {
if (popStack.isEmpty()) {
while (!pushStack.empty()) {
popStack.push(pushStack.pop());
}
}
}
public void add(Integer num) {
if (num == null) {
throw new RuntimeException("num is null");
}
pushStack.push(num);
pushToPopStack();
}
public Integer poll() {
if (pushStack.isEmpty() && popStack.isEmpty()) {
throw new RuntimeException("stack is empty");
}
pushToPopStack();
return popStack.pop();
}
public Integer peek() {
if (pushStack.isEmpty() && popStack.isEmpty()) {
throw new RuntimeException("stack is empty");
}
pushToPopStack();
return popStack.pop();
}
}
~~~
- 基礎
- 數據
- 數據元素
- 數據結構
- 集合結構
- 線性結構
- 樹型結構
- 圖狀結構
- 數據存儲結構
- 算法定義
- 算法效率度量
- 算法效率分析
- 時間復雜度
- O(1)
- O(n)
- O(n2)
- O(logn)
- 空間復雜度
- 線性表
- 數組
- 鏈表
- 串矩陣和廣義表
- 串
- 矩陣
- 廣義表
- 棧和隊列
- 棧
- 隊列
- 樹和二叉樹
- 二叉樹
- 滿二叉樹
- 完全二叉樹
- 哈夫曼樹
- 二叉查找樹-BST樹
- AVL樹
- 紅黑樹
- B樹
- B+樹
- 字典樹
- 跳表
- 算法
- 排序算法
- 冒泡排序
- 選擇排序
- 快速排序
- 插入排序
- 希爾排序
- 歸并排序
- 堆排序
- 基數排序
- 計數排序
- 桶排序
- 查找算法
- 二分查找算法
- Hash算法
- 一致性hash算法
- 算法題
- 001-用兩個棧實現隊列
- 002-只使用棧和遞歸逆序一個棧
- 附錄
- SkipList跳表