2022-11-28 17:10:22 +00:00
|
|
|
// File: array_queue.go
|
|
|
|
// Created Time: 2022-11-28
|
|
|
|
// Author: Reanon (793584285@qq.com)
|
|
|
|
|
|
|
|
package chapter_stack_and_queue
|
|
|
|
|
2022-12-03 12:25:24 +00:00
|
|
|
/* 基于环形数组实现的队列 */
|
2022-11-28 17:10:22 +00:00
|
|
|
type ArrayQueue struct {
|
2022-12-03 12:25:24 +00:00
|
|
|
data []int // 用于存储队列元素的数组
|
2022-11-28 17:10:22 +00:00
|
|
|
capacity int // 队列容量(即最多容量的元素个数)
|
2022-12-03 12:25:24 +00:00
|
|
|
front int // 头指针,指向队首
|
|
|
|
rear int // 尾指针,指向队尾 + 1
|
2022-11-28 17:10:22 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// NewArrayQueue 基于环形数组实现的队列
|
|
|
|
func NewArrayQueue(capacity int) *ArrayQueue {
|
|
|
|
return &ArrayQueue{
|
2022-12-03 12:25:24 +00:00
|
|
|
data: make([]int, capacity),
|
2022-11-28 17:10:22 +00:00
|
|
|
capacity: capacity,
|
2022-12-03 12:25:24 +00:00
|
|
|
front: 0,
|
|
|
|
rear: 0,
|
2022-11-28 17:10:22 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Size 获取队列的长度
|
|
|
|
func (q *ArrayQueue) Size() int {
|
2022-12-03 12:25:24 +00:00
|
|
|
size := (q.capacity + q.rear - q.front) % q.capacity
|
2022-11-28 17:10:22 +00:00
|
|
|
return size
|
|
|
|
}
|
|
|
|
|
|
|
|
// IsEmpty 判断队列是否为空
|
|
|
|
func (q *ArrayQueue) IsEmpty() bool {
|
2022-12-03 12:25:24 +00:00
|
|
|
return q.rear-q.front == 0
|
2022-11-28 17:10:22 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Offer 入队
|
2022-12-03 12:25:24 +00:00
|
|
|
func (q *ArrayQueue) Offer(v int) {
|
|
|
|
// 当 rear == capacity 表示队列已满
|
2022-11-28 17:10:22 +00:00
|
|
|
if q.Size() == q.capacity {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
// 尾结点后添加
|
2022-12-03 12:25:24 +00:00
|
|
|
q.data[q.rear] = v
|
2022-11-28 17:10:22 +00:00
|
|
|
// 尾指针向后移动一位,越过尾部后返回到数组头部
|
2022-12-03 12:25:24 +00:00
|
|
|
q.rear = (q.rear + 1) % q.capacity
|
2022-11-28 17:10:22 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Poll 出队
|
|
|
|
func (q *ArrayQueue) Poll() any {
|
|
|
|
if q.IsEmpty() {
|
|
|
|
return nil
|
|
|
|
}
|
2022-12-03 12:25:24 +00:00
|
|
|
v := q.data[q.front]
|
2022-12-01 16:09:34 +00:00
|
|
|
// 队头指针向后移动一位,若越过尾部则返回到数组头部
|
2022-12-03 12:25:24 +00:00
|
|
|
q.front = (q.front + 1) % q.capacity
|
2022-11-28 17:10:22 +00:00
|
|
|
return v
|
|
|
|
}
|
|
|
|
|
|
|
|
// Peek 访问队首元素
|
|
|
|
func (q *ArrayQueue) Peek() any {
|
|
|
|
if q.IsEmpty() {
|
|
|
|
return nil
|
|
|
|
}
|
2022-12-03 12:25:24 +00:00
|
|
|
v := q.data[q.front]
|
2022-11-28 17:10:22 +00:00
|
|
|
return v
|
|
|
|
}
|
|
|
|
|
2022-12-03 12:25:24 +00:00
|
|
|
// 获取 Slice 用于打印
|
|
|
|
func (s *ArrayQueue) toSlice() []int {
|
|
|
|
return s.data[s.front:s.rear]
|
2022-11-28 17:10:22 +00:00
|
|
|
}
|