package main
import "fmt"
/*
add 增加一個元索 如果隊列已滿,則拋出一個IIIegaISlabEepeplian異常
remove 移除並返回隊列頭部的元素 如果隊列為空,則拋出一個NoSuchElementException異常
element 返回隊列頭部的元素 如果隊列為空,則拋出一個NoSuchElementException異常
offer 添加一個元素並返回true 如果隊列已滿,則返回false
poll 移除並返問隊列頭部的元素 如果隊列為空,則返回null
peek 返回隊列頭部的元素 如果隊列為空,則返回null
put 添加一個元素 如果隊列滿,則阻塞
take 移除並返回隊列頭部的元素 如果隊列為空,則阻塞
*/
type Queue struct {
maxSize int
array []interface{}
front int
rear int
}
//初始化隊列
func NewQueue(size int) *Queue {
if size < 1 {
size = 10 //設置默認值為10
}
return &Queue{
maxSize:size,
array:make([]interface{}, size),
front:-1,
rear:-1,
}
}
func main() {
queue := NewQueue(3)
queue.offer(1)
queue.offer(2)
queue.offer(3)
b := queue.offer(4)
fmt.Println(b)
fmt.Println(queue)
fmt.Println(queue.poll())
fmt.Println(queue.poll())
fmt.Println(queue.poll())
fmt.Println(queue.poll())
queue.offer(5)
queue.offer(6)
queue.offer(7)
b2 := queue.offer(8)
fmt.Println(b2)
fmt.Println(queue)
fmt.Println(queue.poll())
fmt.Println(queue.poll())
fmt.Println(queue.poll())
fmt.Println(queue.poll())
}
//添加數據在隊列
func (this *Queue) offer(val interface{}) bool {
//先判斷隊列是否滿
if (this.rear - this.front) == this.maxSize {
return false
}
this.rear++
this.array[this.rear - this.front - 1] = val
return true
}
//返回隊列頭部元素並移除
func (this *Queue) poll() interface{} {
//判斷隊列是否為空
if this.rear == this.front {
return nil
}
this.front++
var val = this.array[this.front % this.maxSize]
this.array[this.front % this.maxSize] = nil
return val
}