用size解耦pushIndex 和 pollIndex
package linkedTabl
import (
"fmt"
"testing"
)
const queueLimit = 7
type Queue struct { //Ring-Buffer
arr [queueLimit]int
pushI int
pollI int
size int
}
func NewQueue() *Queue {
return &Queue{
arr: [queueLimit]int{},
pushI: 0,
pollI: 0,
size: 0,
}
}
func (q *Queue)Push(value int) int {
if q.size == queueLimit {
return -1
}
q.size++
q.arr[q.pushI] = value
q.pushI = nextIndex(q.pushI)
return 0
}
func (q *Queue)Pop() int {
if q.size == 0 {
return -1
}
q.size--
ans := q.arr[q.pollI]
q.pollI = nextIndex(q.pollI)
return ans
}
func (q *Queue)isEmpty() bool {
return q.size == 0
}
func (q *Queue)isFull() bool {
return q.size == queueLimit
}
func nextIndex(index int) int {
if index < queueLimit - 1 {
return index + 1
}
return 0
}
func TestArrayQueue(t *testing.T) {
q := NewQueue()
q.Push(130)
fmt.Println(q.arr)
q.Push(461)
fmt.Println(q.arr)
q.Push(450)
fmt.Println(q.arr)
q.Push(410)
fmt.Println(q.arr)
q.Push(260)
fmt.Println(q.arr)
q.Push(360)
fmt.Println(q.arr)
q.Push(380)
fmt.Println(q.arr)
fmt.Println(q.isFull())
q.Push(560)
fmt.Println(q.isFull())
fmt.Println(q.Pop())
fmt.Println(q.Pop())
fmt.Println(q.Pop())
fmt.Println(q.Pop())
fmt.Println(q.Pop())
fmt.Println(q.Pop())
fmt.Println(q.Pop())
fmt.Println(q.Pop())
fmt.Println(q.isFull())
fmt.Println(q.isEmpty())
}