(2)Go实现顺序队列

队列是一种线性结构
只能从一端(队尾)添加元素,只能从另一端(队首)取出元素,属于先进先出的结构

// 顺序队列的实现

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://blog.csdn.net/weixin_43456598/article/details/100538518

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值