数据结构-队列
队列(queue)是一种遵循先入先出规则的线性数据结构。顾名思义,队列模拟了排队现象,即新来的人不断加入队列尾部,而位于队列头部的人逐个离开
基于链表的队列
package queue
import "container/list"
type linkedQueue struct { data *list.List }
func NewLinkedQueue() *linkedQueue { return &linkedQueue{ data: list.New(), } } func (q linkedQueue) push(value int) { q.data.PushBack(value) } func (q linkedQueue) pop(value int) any { if q.isEmpty() { return nil } e := q.data.Front() q.data.Remove(e) return e.Value } func (q linkedQueue) peek(value int) any { if q.isEmpty() { return nil } return q.data.Front().Value } func (q linkedQueue) isEmpty() bool { return q.data.Len() == 0 }
func (s *linkedQueue) toList() *list.List { return s.data }
|
基于数组的队列
package queue
type ArrayQueue struct { nums []int front int queSize int queCapacity int }
func NewArrayQueue(queCapacity int) *ArrayQueue { return &ArrayQueue{nums: make([]int, queCapacity), queCapacity: queCapacity, front: 0, queSize: 0} }
func (q *ArrayQueue) size() int { return q.queSize }
func (q *ArrayQueue) isEmpty() bool { return q.queSize == 0 }
func (q *ArrayQueue) push(num int) { if q.queSize == q.queCapacity { return } rear := (q.front + q.queSize) % q.queCapacity q.nums[rear] = num q.queSize++ }
func (q *ArrayQueue) pop() any { num := q.peek() q.front = (q.front + 1) % q.queCapacity q.queSize-- return num }
func (q *ArrayQueue) peek() any { if q.isEmpty() { return nil } return q.nums[q.front] }
func (q *ArrayQueue) toSlice() []int { rear := (q.front + q.queSize) if rear >= q.queCapacity { rear %= q.queCapacity return append(q.nums[q.front:], q.nums[:rear]...) } return q.nums[q.front:rear] } package queue
type ArrayQueue struct { nums []int front int queSize int queCapacity int }
func NewArrayQueue(queCapacity int) *ArrayQueue { return &ArrayQueue{nums: make([]int, queCapacity), queCapacity: queCapacity, front: 0, queSize: 0} }
func (q *ArrayQueue) size() int { return q.queSize }
func (q *ArrayQueue) isEmpty() bool { return q.queSize == 0 }
func (q *ArrayQueue) push(num int) { if q.queSize == q.queCapacity { return } rear := (q.front + q.queSize) % q.queCapacity q.nums[rear] = num q.queSize++ }
func (q *ArrayQueue) pop() any { num := q.peek() q.front = (q.front + 1) % q.queCapacity q.queSize-- return num }
func (q *ArrayQueue) peek() any { if q.isEmpty() { return nil } return q.nums[q.front] }
func (q *ArrayQueue) toSlice() []int { rear := (q.front + q.queSize) if rear >= q.queCapacity { rear %= q.queCapacity return append(q.nums[q.front:], q.nums[:rear]...) } return q.nums[q.front:rear] }
|
Ref