Go语言实现队列 最简单简介的实现队列
直接对[]int进行方法的追加就行了
package main
import "fmt"
// A FIFO queue.
type Queue []int
// Pushes the element into the queue.
// e.g. q.Push(123)
func (q *Queue) Push(v int) {
*q = append(*q, v)
}
// Pops element from head.
func (q *Queue) Pop() int {
head := (*q)[0]
*q = (*q)[1:]
return head
}
// Returns if the queue is empty or not.
func (q *Queue) IsEmpty() bool {
return len(*q) == 0
}
func main() {
q := Queue{1}
q.Push(2)
q.Push(3)
fmt.Println(q.Pop())
fmt.Println(q.Pop())
fmt.Println(q.IsEmpty())
fmt.Println(q.Pop())
fmt.Println(q.IsEmpty())
}
执行结果如下:
1
2
false
3
true
|
请发表评论