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-BasedLinkedList-Based
AdvantagesEfficiency in AccessDynamic Size
Simple ImplementationNo Memory Wastage
Easy Insertions and Deletions
DisadvantagesFixed SizeMemory Overhead
Memory FragmentationLess Efficient Access