Go语言栈与队列:实现与应用
Go语言栈与队列:实现与应用
1. 栈实现
type Stack struct { items []int } func (s *Stack) Push(item int) { s.items = append(s.items, item) } func (s *Stack) Pop() (int, bool) { if len(s.items) == 0 { return 0, false } item := s.items[len(s.items)-1] s.items = s.items[:len(s.items)-1] return item, true } func (s *Stack) Peek() (int, bool) { if len(s.items) == 0 { return 0, false } return s.items[len(s.items)-1], true }2. 队列实现
type Queue struct { items []int } func (q *Queue) Enqueue(item int) { q.items = append(q.items, item) } func (q *Queue) Dequeue() (int, bool) { if len(q.items) == 0 { return 0, false } item := q.items[0] q.items = q.items[1:] return item, true }3. 总结
栈和队列是两种重要的数据结构,分别遵循LIFO和FIFO原则,在算法和系统设计中应用广泛。
