1. 程式人生 > >Go語言(Golang)環形佇列

Go語言(Golang)環形佇列

  1 package main
  2 
  3 import (
  4     "fmt"
  5     "errors"
  6     "os"
  7 )
  8 
  9 //管理環形佇列的結構
 10 type Queue struct {
 11     maxSize int
 12     array [5]int
 13     head int
 14     tail int
 15 }
 16 
 17 //入佇列
 18 func (this *Queue) Push(val int) (err error) {
 19     if this.IsFull() {
 20
return errors.New("佇列已滿!") 21 } 22 this.array[this.tail] = val 23 this.tail = (this.tail + 1) % this.maxSize 24 return 25 } 26 27 //出佇列 28 func (this *Queue) Pop() (val int, err error) { 29 if this.IsEmpty() { 30 return 0, errors.New("佇列為空!") 31 } 32
val = this.array[this.head] 33 this.head = (this.head + 1) % this.maxSize 34 return 35 } 36 37 //顯示佇列 38 func (this *Queue) Show() { 39 if this.IsEmpty() { 40 fmt.Println("佇列為空!") 41 } 42 temp := this.head 43 for i := 0; i < this.Size(); i++ { 44 fmt.Printf("
array[%d]:%d\t",temp,this.array[temp]) 45 temp = (temp + 1) % this.maxSize 46 } 47 48 } 49 50 //判斷佇列是否已滿 51 func (this *Queue) IsFull() bool { 52 return (this.tail + 1) % this.maxSize == this.head 53 } 54 55 //判斷佇列是否為空 56 func (this *Queue) IsEmpty() bool { 57 return this.head == this.tail 58 } 59 60 //查詢有多少個佇列 61 func (this *Queue) Size() int { 62 return (this.tail + this.maxSize - this.head) % this.maxSize 63 } 64 65 66 67 68 func main(){ 69 70 quque := &Queue { 71 maxSize : 5, 72 head : 0, 73 tail : 0, 74 } 75 76 var xz string 77 var number int 78 for { 79 fmt.Println() 80 fmt.Println("1.新增佇列請輸入add") 81 fmt.Println("2.獲取佇列請輸入get") 82 fmt.Println("3.顯示佇列請輸入show") 83 fmt.Println("4.輸入exit退出") 84 fmt.Scanln(&xz) 85 86 switch xz { 87 case "add" : 88 fmt.Println("輸入你要入列的數:") 89 fmt.Scanln(&number) 90 err := quque.Push(number) 91 if err != nil { 92 fmt.Println(err.Error()) 93 } else { 94 fmt.Printf("加入佇列成功!\n") 95 } 96 case "get" : 97 val, err := quque.Pop() 98 if err != nil { 99 fmt.Println(err.Error()) 100 } else { 101 fmt.Printf("佇列已取出:%d",val) 102 } 103 104 case "show" : 105 quque.Show() 106 fmt.Println() 107 case "exit" : 108 os.Exit(0) 109 } 110 } 111 }