顺序队列的操作有以下基本操作:
- 初始化一个队列
- 测试队列是否为空
- 取当前队头元素
- 队列的插入(进队)
- 队列的删除(出队)
class Queen{
constructor () {
this.front = -1
this.rear = -1
this.M = 100
this.queen = new Array(this.M)
this.getQitem = null
this.delQitem = null
}
initialQ() {
return new Queen()
}
emptyQ() {
return this.front == this.rear
}
getQ() {
if ( this.emptyQ() ) {
return 0
} else {
this.getQitem = this.queen[this.front+1]
return 1
}
}
addQ(item) {
if ( this.rear == this.M-1 ) {
return 0
} else {
this.queen[++this.rear] = item
return 1
}
}
delQ() {
if ( this.emptyQ() ) {
return 0
} else {
this.delQitem = this.queen[++this.front]
return 1
}
}
delQ1() {
if ( this.emptyQ() ) {
return 0
} else {
this.delQitem = this.queen[0]
for (let i = 0; i < this.rear; i++) {
this.queen[i] = this.queen[i+1]
}
return 1
}
}
addCQ(item) {
if ( (this.rear+1)%this.M == this.front ) { //循环队列已满
return 0
} else {
this.queen[++this.rear%this.M] = item
return 1
}
}
delCQ() {
if ( this.front == this.rear ) {
return 0
} else {
this.front = (this.front + 1) % this.M
this.delItem = this.queen[this.front]
return 1
}
}
}
测试:
var queen = new Queen()
queen.initialQ()
queen.addQ(1)
queen.addQ(2)
queen.addQ(3)
queen.addQ(4)
queen.addQ(5)
queen.emptyQ()
queen.getQ()
queen.delQ()
queen.addCQ(1)
queen.delCQ()
应该说明:这里的所谓删除,并不是把队头元素从原存储位置上物理地删除,只是将队头指针向队尾方向移动一个位置,这样,原来那个队头元素就别惹味不再包含在队列中了。
网友评论