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

135 阅读1分钟

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

队列

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

数据实现

graph LR
    3 --对头--- 5
    5 --- 1 
    1 --- 4 
    4 --- 9 
    9 --队尾--- 6

链表实现

graph LR
    3 --对头-->5
    5 --> 1 
    1 --> 4 
    4 --> 9 
    9 --> 6
    6 --队尾--> null

入队

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

graph LR
    3 --对头-->5
    5 --> 1 
    1 --> 4 
    4 --> 9 
    9 --> 6
    6 --队尾--> 7

出队

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

graph LR
    5 --对头--> 1 
    1 --> 4 
    4 --> 9 
    9 --> 6
    6 --队尾--> 7

链表队列具体实现

节点类

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