package main
import (
"errors"
"fmt"
"os"
)
type CircleQueue struct {
head int
tail int
array [5]int
maxSize int
}
func (this *CircleQueue) IsFull() bool {
return (this.tail+1)%this.maxSize == this.head
}
func (this *CircleQueue) IsEmpty() bool {
return this.tail == this.head
}
func (this *CircleQueue) Size() int {
return (this.tail + this.maxSize - this.head) % this.maxSize
}
func (this *CircleQueue) Push(val int) (err error) {
if this.IsFull() {
return errors.New("Queue Full")
}
this.array[this.tail] = val
this.tail = (this.tail + 1) % this.maxSize
return
}
func (this *CircleQueue) Pop() (v int, err error) {
if this.IsEmpty() {
return -2, errors.New("Queue is Empty.")
}
v = this.array[this.head]
this.head = this.head + 1
return
}
func (this *CircleQueue) List() {
fmt.Println("Circle Queue as tHIS queue.")
size := this.Size()
if size == 0 {
fmt.Println("Your Queue Is Empty.")
}
temp := this.head
for i := 0; i < size; i++ {
fmt.Printf("array[%d]=%d", temp, this.array[temp])
temp = (temp + 1) % this.maxSize
}
}
func main() {
// 1,2,3,4,0
// 滿:
// (tail + 1) % maxsize == head
// 空:
// tail == head
// 有多少個:
// (tail + maxsize -head) % maxsize
array := &CircleQueue{
head: 0,
tail: 0,
maxSize: 5,
}
var (
key string
value int
err error
)
for {
fmt.Println("push: for push value into array")
fmt.Println("pop: for pop value into array")
fmt.Println("list: for show value into array")
fmt.Println("exit:")
fmt.Println("Please Give me Your KeyWord.")
fmt.Scanln(&key)
switch key {
case "push":
fmt.Println("Please give me you value.")
fmt.Scanln(&value)
if err = array.Push(value); err != nil {
fmt.Println(err)
} else {
fmt.Println("Add this array Successed.")
}
case "list":
array.List()
case "pop":
if val, err := array.Pop(); err != nil {
fmt.Println(err)
} else {
fmt.Println("\nvalue:", val)
}
case "exit":
os.Exit(0)
case "bianli":
fmt.Println(array.array)
}
}
}