队列: 队列是一种特殊的线性表,特殊性表现它只能在表的前端 front
进行删除操作,只能在表的后端 rear
进行添加操作。 先进先出(FIFO)
- js代码实现(链式队列的实现):
// 以构造函数的方式来实现 ,也可使用 class 来实现
funtion LinkedQueue() {
// 定义一个节点结构
let Node = function(ele) {
this.ele = ele;
this.next = null;
}
let length = 0, front, rear;
// 队尾添加操作
this.push = function(ele) {
let node = new Node(ele);
if(length == 0) {
front = node;
} else {
let temp = rear;
temp.next = node;
}
rear = node;
length++;
return true;
}
// 队首删除操作
this.pop = function() {
let temp = front;
front = front.next;
length--;
temp.next = null;
return temp;
}
// 队列大小
this.size = function() {
return length;
}
// 获取头元素
this.getFront = function() {
return front;
}
// 获取尾元素
this.getRear = function() {
return rear;
}
// 读取队列元素 toString
this.toString = function() {
let str = '', temp = front;
while(temp) {
str = str + temp.ele + ' ';
temp = temp.next;
}
return str;
}
// 清空队列
this.clear = function() {
front = null;
rear = null;
length = 0;
return true;
}
}
// 测试使用
let myQueue = new LinkedQueue();
myQueue.push(1);
myQueue.push(2);
myQueue.push(3);
console.log(myQueue.toString())
console.log(myQueue.pop());
console.log(myQueue.toString())
- 顺序队列存储:利用js内置的Array来实现
function ArrayQueue() {
var arr = [];
this.push = function(ele) {
arr.push(ele);
return true;
}
this.pop = function() {
return arr.shift();
}
this.getFront = function() {
return arr[0];
}
this.getRear = function() {
return arr[arr.length - 1];
}
this.clear = function() {
arr = [];
/*
arr.length = 0;
arr.splice(0);
*/
}
this.size = function() {
return arr.length;
}
}