第五章 Caché 算法与数据结构 队列原理

文章目录

第五章 Caché 算法与数据结构 队列原理

队列

队列是一种线性数据结构,不同于栈的先入后出,队列中的元素只能先入先出。队列的出口端叫做对头,队列的入口端叫做队尾。

数据实现

对头
队尾
1
3
4
5
6
9

链表实现

对头
队尾
1
3
4
5
6
9
null

入队

入队就是把新元素放入队列中,只允许在队尾的位置放入元素,新元素的下一个位置将会成为队尾。例如7入队。

对头
队尾
1
3
4
5
6
7
9

出队

出队操作就是把元素移出队列,只允许在头一侧移除元素,出队元素后的一个元素将会成为新的列头。例如3出队。

对头
队尾
1
4
5
6
7
9

链表队列具体实现

节点类

Class PHA.YX.Arithmetic.LinkedQueue.Node Extends %RegisteredObject
{

Property next As PHA.YX.Arithmetic.LinkedQueue.Node;

Property element;

Method %OnNew(next As PHA.YX.Arithmetic.LinkedQueue.Node, element) As %Status [ Private, ServerOnly = 1 ]
{
	s $this.next = next
	s $this.element = element
	Quit $$$OK
}

Method getNext() As PHA.YX.Arithmetic.LinkedQueue.Node
{
	q ..next
}

Method setNext(next As PHA.YX.Arithmetic.LinkedQueue.Node)
{
	s $this.next = next
}

Method getElement() As PHA.YX.Arithmetic.LinkedQueue.Node
{
	q ..element
}

Method setElement(element)
{
	s $this.element = element
}

}

链表队列类

Class PHA.YX.Arithmetic.LinkedQueue Extends %RegisteredObject
{

Property front As PHA.YX.Arithmetic.LinkedQueue.Node;

Property rail As PHA.YX.Arithmetic.LinkedQueue.Node;

Property size As %Integer [ InitialExpression = 0 ];

Method isEmpty() As %Boolean
{
	q $s(..size = 0 : $$$YES, 1 : $$$NO)
}

Method addQueue(ele)
{
	i ..size = 0 d
	.s ..front = ##class(PHA.YX.Arithmetic.LinkedQueue.Node).%New("",ele)
	.s ..rail = ..front
	.s ..size = ..size + 1
	e  d
	.s s = ##class(PHA.YX.Arithmetic.LinkedQueue.Node).%New("",ele)
	.d ..rail.setNext(s)
	.s ..rail = s
	.s ..size = ..size + 1
}

Method deleteQueue()
{
	i ..isEmpty() d
	.throw ##class(PHA.COM.MOB.Exception).%New("当前队列为空!")
	s ele = ..front.getElement()
	s ..front = ..front.next
	s ..size = ..size - 1
	q ele
}

}

调用


/// w ##class(PHA.YX.Arithmetic).LinkedQueue()
ClassMethod LinkedQueue()
{
	#dim linkedQueue as PHA.YX.Arithmetic.LinkedQueue = ##class(PHA.YX.Arithmetic.LinkedQueue).%New()
	d linkedQueue.addQueue(1)
	d linkedQueue.addQueue("a")
	d linkedQueue.addQueue(2)
	w linkedQueue.deleteQueue(),!
	w linkedQueue.deleteQueue(),!
	d linkedQueue.addQueue("b")
	w linkedQueue.deleteQueue(),!
	w linkedQueue.deleteQueue(),!
	q ""
}
DHC-APP>w ##class(PHA.YX.Arithmetic).LinkedQueue()
1
a
2
b
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

yaoxin521123

谢谢您的支持!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值