1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
| package main
import ( "fmt" "errors" )
type queue struct { head int tail int array [4]int maxCap int }
func (q *queue) isFull() bool { if (q.tail + 1) % q.maxCap == q.head { fmt.Println("队列已满") return true } return false }
func (q *queue) isEmpty() bool { if q.tail == q.head { fmt.Println("队列为空") return true } return false }
func (q *queue) pushQueue(value int) {
if q.isFull() { fmt.Println("队列满了") } else { q.array[q.tail] = value q.tail = (q.tail + 1) % q.maxCap }
}
func (q *queue) popQueue() error{ if q.isEmpty() { fmt.Println("队列为空") return errors.New("队列为空") }
val := q.array[q.head] q.head = (q.head + 1) % q.maxCap
fmt.Printf("弹出了%v\n", val) return nil
}
func (q *queue) showQueue() { count := (q.tail + q.maxCap - q.head) % q.maxCap if count == 0 { fmt.Println("当前为空队列") return } tempHead := q.head for i:=0 ; i<count; i++ { fmt.Printf("q.array[%v], 值为%v\n", tempHead, q.array[tempHead]) tempHead = (tempHead + 1) % q.maxCap } }
func main() { Q := &queue{ head:0, tail:0, maxCap:4, } Q.pushQueue(4) Q.pushQueue(5) Q.pushQueue(3) fmt.Println("push 4, 5, 3后为") Q.showQueue()
Q.popQueue() Q.popQueue() fmt.Println("pop两次后为") Q.showQueue()
}
|