Directory Structure:
circlequeue.go
package queue import ( "errors" "fmt" ) // CircleQueue ring queue type CircleQueue struct { MaxSize int Array [5]int Front int Rear int } // the Push to add a value to the queue FUNC (Q * CircleQueue) the Push (Val int ) (ERR error) { // first determine whether the queue is full IF q.IsFull () { return errors.New ( " Queue Full " ) } q.Array [q.Rear] = Val // the tail contains no elements // q.Rear ++ q.Rear = (+ q.Rear. 1)% q.MaxSize return } // Pop obtain a value FUNC (Q * CircleQueue) Pop () (Val int , ERR error) { IF q.IsEmpty () { return - . 1 , errors.New ( " queue empty " ) } // first team contains elements Val = q.Array [q.Front] // q.Front ++ q.Front = (q.Front + 1)% q.MaxSize return Val, ERR } // IsFull if the queue is full FUNC (Q * CircleQueue) IsFull () BOOL { return (+ q.Rear. 1) ==% q.MaxSize q.Front } // the IsEmpty queue is empty FUNC (Q * CircleQueue) the IsEmpty () BOOL { return q.Front == q.Rear } //Size 队列的大小 func (q *CircleQueue) Size() int { return (q.Rear + q.MaxSize - q.Front) % q.MaxSize } // the Show Display queue FUNC (Q * CircleQueue) the Show () { // remove the current number of elements in the queue size: = q.Size () IF size == 0 { fmt.Println ( " queue empty " ) } // auxiliary variables point Front tmpFront: = q.Front for I: = 0 ; I <size; I ++ { fmt.Printf("queue[%d]=%v\t", tmpFront, q.Array[tmpFront]) tmpFront = (tmpFront + 1) % q.MaxSize } }
main.go
package main import ( "fmt" "go_code/data_structure/queue" "os" ) func main() { var key string var val int q := &queue.CircleQueue{ MaxSize: 5, Front: 0, Rear: 0, } for { fmt.Println("------------------------------") fmt.Println ( " 1. Enter add data to a queue represents push " ) fmt.Println ( " 2. pop retrieves data from the input queue " ) fmt.Println ( " 3. Enter show shows a display queue " ) fmt.Println ( " 4. Enter exit for quit " ) fmt.Println("------------------------------") fmt.Scanln(&key) switch key { case "push": fmt.Println ( " Please enter a value to be added: " ) fmt.Scanln(&val) err := q.Push(val) if err != nil { fmt.Println(err) } else { fmt.Println ( " Add success " ) fmt.Println("Rear:", q.Rear) } case "pop": val, err := q.Pop() if err != nil { fmt.Println(err) } else { fmt.Println ( " to get the value: " , Val) fmt.Println("Front:", q.Front) } case "show": q.Show() fmt.Println() case "exit": os.Exit ( 0 ) } } }
Note where the red mark, which is the core of the circular queue.