Skip to content

队列 ​

基础与数据结构

说明 ​

先进先出地处理元素;用头下标避免反复移动整个切片。

分析 ​

队列从尾部加入、从头部取出,保证先到先处理。示例以 head 标记已消费位置,避免每次 Pop 都复制剩余元素。

head表示下一个未消费位置。取出4后不移动7,因此Pop为常数时间;但底层长度不会随消费自动下降,长期使用需压缩已消费前段或采用环形缓冲。

查看图表代码

适用前提与边界 ​

长期运行时要定期压缩或重置底层切片,否则已消费的前段可能继续占内存。 空队列返回(0,false),因此不能仅用返回值0判断是否有元素;已消费前缀需按运行时长安排回收。

示例输入与调用 ​

go
queue := new(Queue)
	queue.Push(4)
	queue.Push(7)
	value, ok := queue.Pop()
	fmt.Println(value, ok)

运行输出 ​

text
4 true

完整 Go 示例 ​

go
package main

import "fmt"

type Queue struct {
	items []int
	head  int
}

func (q *Queue) Push(x int) {
	q.items = append(q.items, x)
}
func (q *Queue) Pop() (int, bool) {
	if q.head == len(q.items) {
		return 0, false
	}
	x := q.items[q.head]
	q.head++
	return x, true
}

func main() {
	queue := new(Queue)
	queue.Push(4)
	queue.Push(7)
	value, ok := queue.Pop()
	fmt.Println(value, ok)
}

继续阅读