golang实现的循环队列
package main
import "fmt"
type Queue struct {
arr []int
front int
rear int
}
func NewQueue(maxSize int) *Queue{
return &Queue{
arr: make([]int,maxSize),
front: 0,
rear: 0,
}
}
func (q *Queue)Push(data int) {
q.arr[q.rear] = data
q.rear = (q.rear + 1) % len(q.arr)
}
func (q *Queue)Pop() int {
tmp := q.arr[q.front]
q.front = (q.front + 1) % len(q.arr)
return tmp
}
func (q *Queue)IsEmpty() bool {
return q.front == q.rear
}
func (q *Queue)IsFull() bool {
return q.front == (q.rear + 1) % len(q.arr)
}
func (q *Queue)Length() int {
return (q.rear - q.front + len(q.arr)) % len(q.arr)
}
func main() {
q := NewQueue(10)
var i int
for !q.IsFull() {
q.Push(i)
fmt.Println("Push ",i)
fmt.Println("len ",q.Length())
i++
}
for !q.IsEmpty() {
data := q.Pop()
fmt.Println("Pop ",data)
}
}