队列是一种线性结构
只能从一端(队尾)添加元素,只能从另一端(队首)取出元素,属于先进先出的结构
// 顺序队列的实现
type queue interface{}
type sliceQueue struct {
queues []queue
}
func NewQueue() *sliceQueue {
return &sliceQueue{}
}
func (i *sliceQueue) Len() int {
return len(i.queues)
}
func (i *sliceQueue) Cap() int {
return cap(i.queues)
}
func (i *sliceQueue) Enqueue(item interface{}) {
i.queues = append(i.queues, item)
}
func (i *sliceQueue) Dequeue() (queue, error) {
if i.Len() == 0 {
return nil, errors.New(
"failed to dequeue,queue is empty ")
}
queue := i.queues[0]
i.queues = i.queues[1:]
return queue, nil
}
func (i *sliceQueue) GetFront() (queue, error) {
if i.Len() == 0 {
return nil, errors.New(
"failed to getFront,queue is empty ")
}
return i.queues[0], nil
}
func (i *sliceQueue) IsEmpty() bool {
return i.Len() == 0
}
// 队列测试
func main() {
a := queue3.NewQueue()
for i := 0; i < 5; i++ {
a.Enqueue(strconv.Itoa(i) + "-hello toilet ")
}
fmt.Printf("isEmpty: %v, len=%v, cap=%v, getFront=%v\n",
a.IsEmpty(), a.Len(), a.Cap(), fmt.Sprintln(a.GetFront()))
fmt.Printf("isEmpty: %v, len=%v, cap=%v, dequeue=%v\n",
a.IsEmpty(), a.Len(), a.Cap(), fmt.Sprintln(a.Dequeue()))
fmt.Printf("isEmpty: %v, len=%v, cap=%v, dequeue=%v\n",
a.IsEmpty(), a.Len(), a.Cap(), fmt.Sprintln(a.Dequeue()))
fmt.Printf("isEmpty: %v, len=%v, cap=%v, dequeue=%v\n",
a.IsEmpty(), a.Len(), a.Cap(), fmt.Sprintln(a.Dequeue()))
fmt.Printf("isEmpty: %v, len=%v, cap=%v, dequeue=%v\n",
a.IsEmpty(), a.Len(), a.Cap(), fmt.Sprintln(a.Dequeue()))
fmt.Printf("isEmpty: %v, len=%v, cap=%v, dequeue=%v\n",
a.IsEmpty(), a.Len(), a.Cap(), fmt.Sprintln(a.Dequeue()))
fmt.Printf("isEmpty: %v, len=%v, cap=%v, dequeue=%v\n",
a.IsEmpty(), a.Len(), a.Cap(), fmt.Sprintln(a.Dequeue()))
fmt.Printf("isEmpty: %v, len=%v, cap=%v, getFront=%v\n",
a.IsEmpty(), a.Len(), a.Cap(), fmt.Sprintln(a.GetFront()))
}
// 测试结果
isEmpty: false, len=5, cap=8, getFront=0-hello toilet <nil>
isEmpty: false, len=5, cap=8, dequeue=0-hello toilet <nil>
isEmpty: false, len=4, cap=7, dequeue=1-hello toilet <nil>
isEmpty: false, len=3, cap=6, dequeue=2-hello toilet <nil>
isEmpty: false, len=2, cap=5, dequeue=3-hello toilet <nil>
isEmpty: false, len=1, cap=4, dequeue=4-hello toilet <nil>
isEmpty: true, len=0, cap=3, dequeue=<nil> failed to dequeue,queue is empty
isEmpty: true, len=0, cap=3, getFront=<nil> failed to getFront,queue is empty
顺序队列的缺陷是每次取出元素,都要重新遍历一次队列,时间复杂度为O(n),冗余操作太多
下面链接有更好的实现方法,循环队列
https://www.jianshu.com/p/8a26bedb48a1
有bug欢迎指出,转载请注明出处。
网友评论