Stack
Stack(堆疊)是一種後進先出(LIFO - Last In First Out)的資料結構。
Basic Operations
Push- 將元素加入堆疊頂端Pop- 移除並返回堆疊頂端元素Peek- 查看堆疊頂端元素(不移除)IsEmpty- 檢查堆疊是否為空Size/Length- 返回堆疊中的元素數量Search- 搜尋特定元素Display/PrintStack- 顯示堆疊內容
Applications
- Reverse a word - 反轉字串
- Browsers - 瀏覽器的上一頁/下一頁功能
- Compilers - 計算表達式的值,例如
2 + 4 / 5 * (7 - 9)轉換為前綴或後綴表示法
Implementation
Stack implemented by Array
type Array[T any] struct {
elements []T
}Stack implemented by LinkedList
type Node struct {
Val any
Next *Node
}
type Stack struct {
top *Node
length int
}Stack implemented by Std List
import "container/list"
type StackList[T any] struct {
stack *list.List
}Comparison
| Array-Based | LinkedList-Based | |
|---|---|---|
| Advantages | Efficiency in Access | Dynamic Size |
| Simple Implementation | No Memory Wastage | |
| Easy Insertions and Deletions | ||
| Disadvantages | Fixed Size | Memory Overhead |
| Memory Fragmentation | Less Efficient Access |