Go数据结构与算法-实现数组队列


title: Go数据结构与算法-实现数组队列
tags: go,算法


介绍

队列(queue), 是一种先进先出的数据结构。通常用数据或者链表来实现队列。 队列只允许在后端插入(进队),首端删除(出队)。在日常生活中非常常见:比如去银行排队办理业务. 在计算机中也极其常见, 很多情况下,当有大量任务需要完成时, 就会把任务暂时加入到 任务队列中, 执行一个删除一个,继续执行下一个任务.

性质:

  • 先进先出
  • 只能从队尾插入数据

演示

我们使用切片简单的演示下队列


package main
type  MyQueue interface {
	Size()int   //大小
	Front()interface{} //第一个元素
	End()interface{} //最后一个元素
	IsEmpty() bool //是否为空
	Enqueue(data interface{}) //入队
	Dequeue() interface{} //出对
	Clear()//清空
}

type  Queue struct{
	datastore []interface{}
	theSize int
}
func(myqueue *Queue) Clear(){
	myqueue.datastore =make([]interface{},0)  //开辟内存
	myqueue.theSize=0
}

func  NewQueue() *Queue{
	myqueue:=new(Queue)
	myqueue.Clear()
	return myqueue

}
func(myqueue *Queue) Size()int   {
	return  myqueue.theSize //大小
}
func(myqueue *Queue) Front()interface{} {
	if myqueue.Size()==0{ //判断是否为空
		return nil
	}
	return myqueue.datastore[0]
}
func(myqueue *Queue) End()interface{} {
	if myqueue.Size()==0{ //判断是否为空
		return nil
	}
	return myqueue.datastore[myqueue.theSize-1]
}
func(myqueue *Queue) IsEmpty() bool{
	return  myqueue.theSize==0
}
func(myqueue *Queue) Enqueue(data interface{}) {
	myqueue.datastore=append( myqueue.datastore,data) //入队
	myqueue.theSize++
}
func(myqueue *Queue) Dequeue() interface{} {
	if myqueue.Size()==0{ //判断是否为空
		return nil
	}
	data:=myqueue.datastore[0]
	if  myqueue.Size()>1 {
		myqueue.datastore = myqueue.datastore[1:myqueue.theSize] //截取
	}
	myqueue.theSize--
	return  data
}

func main(){
	myq:=NewQueue()
	myq.Enqueue(1)
	myq.Enqueue(2)
	myq.Enqueue(3)
	myq.Enqueue(4)
	fmt.Println(myq.Size())
	fmt.Println(myq.Dequeue())
	fmt.Println(myq.Dequeue())
	fmt.Println(myq.Dequeue())
	fmt.Println(myq.Dequeue())
	fmt.Println(myq.Size())
	myq.Enqueue(1)
	myq.Enqueue(2)
	myq.Enqueue(3)
	myq.Enqueue(4)
	myq.Clear()
	fmt.Println(myq.Size())
	
}


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值