//队列分顺序结构,链式结构。
//顺序结构中。 使用循环结构,且队列最大长度要小于数组的最大容量
function QueueArray() {
this.maxLength = 0;
this.mQueueArray = null;
//头索引
this.topIndex = 0;
//尾部索引+1 是尾部始终保留一个空闲空间
this.tailIndex = 0;
//队列元素个数
this.count = 0;
//记录队列中排到的序号
this.mNodeCount = 0;
this.init = function (maxLength) {
if (this.mQueueArray == null) {
this.mQueueArray = new Array(maxLength);
this.maxLength = maxLength;
}
}
this.getSize = function () {
return this.count;
}
this.getTopIndex = function () {
return this.topIndex;
}
this.getTailIndex = function () {
return this.tailIndex;
}
this.getQuene = function () {
return this.mQueueArray;
}
this.getOldCount = function () {
return this.mNodeCount;
}
/**
* 判断队列是否满员。满员状态时。空空余一个元素空间
*/
this.isEmpty = function () {
let index = 0;
if (this.tailIndex + 1 >= this.maxLength) {
index = 0;
} else {
index = this.tailIndex + 1;
}
return this.mQueueArray[index] ? false : true;
}
this.push = function (data) {
if (!this.isEmpty()) {
return "队列满了";
}
if (this.count == 0) {
this.mQueueArray[0] = data;
this.topIndex = 0;
this.tailIndex++;
} else {
this.mQueueArray[this.tailIndex] = data;
this.tailIndex++;
if (this.tailIndex >= this.maxLength) {
this.tailIndex = 0;
}
}
this.count++;
this.mNodeCount++;
}
this.pop = function () {
if (this.count <= 0) return "队列为空";
let node = this.mQueueArray[this.topIndex];
this.mQueueArray[this.topIndex] = null;
this.topIndex++;
if (this.topIndex >= this.maxLength) {
this.topIndex = 0;
}
this.count--;
return node;
}
}
/**
* 链式队列 头出尾进
*/
function QueueLink() {
function Node(element) {
this.element = element;
this.next = null;
}
this.length = 0;
this.head = null;
this.tail = null;
this.getHead = function () {
return this.head;
}
this.getTail = function () {
return this.tail;
}
this.size = function () {
return this.length;
}
this.isEmpty = function () {
return this.length == 0;
}
this.push = function (element) {
let node = new Node(element);
if (this.head == null) {
this.head = node;
this.tail = node;
} else {
this.tail.next = node;
this.tail = node;
}
this.length++;
}
this.pop = function () {
if (this.isEmpty()) return "队列为空";
let node = null;
if (this.length == 1) {
node = this.head;
this.tail = null;
this.head = null;
} else {
node = this.head;
this.head = this.head.next;
}
this.length--;
return node;
}
this.toString = function () {
let current = this.head;
let s = '';
while (current) {
let next = current.next;
next = next ? next.element : 'null';
s += `[element:${current.element},next:${next}]`;
current = current.next;
}
return s;
}
}