- 栈
在栈顶删除和插入 后进先出
参考文章
//封装一个栈
function Stack(){
this.items = [];
Stack.prototype.push = function(ele){
//向栈顶插入元素
this.items.push(ele);
};
Stack.prototype.pop = function(){
//向栈顶删除元素,返回删除的元素
return this.items.pop();
};
Stack.prototype.peek = function () {
//查看栈顶元素
return this.items[this.items.length -1]
};
Stack.prototype.isEmpty = function () {
//判断栈是否为空
return this.items.length == 0;
};
Stack.prototype.size = function () {
//返回栈的元素个数
return this.items.length;
};
Stack.prototype.toString = function () {
//转换成字符串
return this.items.join("")
}
}
let stack = new Stack();
stack.items = [22,3432,232];
stack.push(111);
console.log(stack);//Stack { items: [ 22, 3432, 232, 111 ] }
console.log(stack.pop());//111
console.log(stack.isEmpty());//false
console.log(stack.toString());//223432232
- 队列
在前面删除 后面插入 先进先出
参考文章
//封装队列
function Queue(){
this.items = [];
Queue.prototype.enqueue = function (ele) {
//在队列尾部插入新元素
this.items.push(ele);
};
Queue.prototype.delqueue = function(){
//在队列头部删除元素
this.items.shift();
;
Queue.prototype.fort = function () {
//查看队列头部第一个元素
return this.items[0]
};
}
- 优先级队列
普通的队列插入一个元素, 数据会被放在后端. 并且需要前面所有的元素都处理完成后才会处理前面的数据。但是优先级队列, 在插入一个元素的时候会考虑该数据的优先级.(和其他数据优先级进行比较)
优先级队列和普通队列最大的区别就是在插入时要考虑元素的优先级。
function PrimaryQueue(){
function QueueElement(ele,primary){
this.ele = ele;
this.primary = primary;
}
this.items = [];
PrimaryQueue.prototype.enterqueue = function(ele,primary){
let queue = new QueueElement(ele,primary);
//判断队列是否为空
if(this.items.length == 0){
this.items.push(queue)
}else{
let flag = false;
for(let i =0; i<this.items.length; i++){
//遍历 将当前要插入的元素的优先级和每个元素的优先级进行比较
if(queue.primary < this.items[i].primary){
// 假设 优先级数字越小,优先级越高
this.items.splice(i,0,queue);
flag = true;
break;
}
}
// 遍历完所有的元素, 优先级都小于新插入的元素时, 就插入到最后
if(!flag){
this.items.push(queue)
}
}
};
}
let qe = new PrimaryQueue();
qe.enterqueue("aaa",1);
qe.enterqueue("sa",111);
qe.enterqueue('asss',40);
console.log(qe);
/*
PrimaryQueue {
items:
[ QueueElement { ele: 'aaa', primary: 1 },
QueueElement { ele: 'asss', primary: 40 },
QueueElement { ele: 'sa', primary: 111 } ] }
*/