Stack
- Stack
![Stack<sup
><a href='#ref-stack-img'>[1]</a></sup>](../../assets/stack.webp)
介紹
- 堆疊 或 棧
- 資料遵從 LIFO (Last-In-First-Out)「先進後出」的原則
- 想像你正在放一疊書進去一個箱子,當你往這個箱子裡上放一本新書時,你只能放在最頂端。而要拿出一本書時也只能從最頂端拿,這個箱子就是 Stack
- 可由 Array 或 Linked-List 實作
- 支援3個操作
| Operation | Time Complexty | Description |
|---|---|---|
| Peek() | 查看最頂端的元素 | |
| Push() | 從最頂端新增一個元素 | |
| Pop() | 從最頂端移除一個元素 |
C++ STL - std::stack
- C++ 的 STL(Standard Library) 有提供現成的 std::stack
- Constructor
Stack(STL ver.) 1
2
3
4
5
6
7
8
9
10// Default Constructor
std::stack<int> myStack; // Creates an empty stack of integers
// Constructor with Container
std::vector<int> myVector = {10, 20, 30};
std::stack<int, std::vector<int>> stackFromVector(myVector); // Creates a stack initialized with elements from the vector
// Copy Constructor
std::stack<int> originalStack = /* ... */;
std::stack<int> newStack(originalStack); // Creates a copy of originalStack - Operations
Stack(STL ver.) 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19std::stack<int> myStack;
// 從最頂端新增一個元素
std::cout << myStack.push(1) << "\n"; // Stack(from bottom to top): 1
std::cout << myStack.push(3) << "\n"; // Stack(from bottom to top): 1 3
std::cout << myStack.push(5) << "\n"; // Stack(from bottom to top): 1 3 5
std::cout << myStack.push(7) << "\n"; // Stack(from bottom to top): 1 3 5 7
std::cout << myStack.push(9) << "\n"; // Stack(from bottom to top): 1 3 5 7 9
// 從最頂端移除一個元素 (不會回傳元素)
myStack.pop() // Stack(from bottom to top): 1 3 5 7
myStack.pop() // Stack(from bottom to top): 1 3 5
// 查看最頂端的元素
std::cout << myStack.top() << "\n"; // 5
// 查看stack的大小(元素數量)
std::cout << myStack.size() << "\n"; // 3
// 查看stack是否為空
std::cout << myStack.empty() << "\n"; // False
實作 - Array ver.
1 | class Stack{ |
1 |
|
實作 - Linked-List ver.
1 | class Node{ |
相關演算法 Related Algorithm
Will be updated later…
- DFS
- Infix to Postfix
- Parentheses Matching
Reference
- [1] Stack Image
Comments