栈
封装
function Stack(item) {
this.items = [];
Stack.prototype.push = function (item) {
this.items.push(item)
}
Stack.prototype.pop = function () {
return this.items.pop()
}
Stack.prototype.TopItem = function () {
return this.items[this.items.length - 1]
}
Stack.prototype.isEmpty = function () {
return this.items.length == 0
}
Stack.prototype.Num = function () {
return this.items.length
}
Stack.prototype.toString = function () {
return this.items.join(' ')
}
}
var pp = new Stack()
利用栈结构计算十进制转化为二进制
function toChange(num){
let record=new Stack()
while(num/2>0){
record.push(num%2);
var num=Math.floor(num/2)
}
var rs='';
while(!record.isEmpty()){
rs+=record.pop()
}
return rs
}
toChange(50)
队列
- 只允许在前端删除,后端插入,先进先出
- 也是一种受限的线性结构
- FIFO(first in first out)
队列的封装
function Queue(item){
this.items=[]
Queue.prototype.enqueue=function(item){
this.items.push(item)
}
Queue.prototype.dequeue=function(){
return this.items.shift()
}
Queue.prototype.front=function(){
return this.items[0]
}
Queue.prototype.isEmpty=function(){
return this.items.length==0
}
Queue.prototype.size=function(){
return this.items.length
}
Queue.prototype.toString=function(){
return this.items.join(' ')
}
}
var cc=new Queue()
击鼓串花
function passGame(namelist,num){
let ccc=new Queue()
for(var i=0;i<namelist.length;i++){
ccc.enqueue(namelist[i])
}
while(ccc.size>1){
for(var i=0;i<num-1;i++){
ccc.enqueue(ccc.dequeue())
}
ccc.dequeue()
}
return ccc.front()
}
优先级队列
- 插入元素的时候,会考虑数据的优先级再进行排列
- 只有插入不一样,别的都和普通队列一样
优先级队列的封装
function PriorityQueue() {
this.items = [];
function QueueElement(ele, pro) {
this.ele = ele;
this.pro = pro;
}
PriorityQueue.prototype.enqueue = function (ele, pro) {
var item = new QueueElement(ele, pro)
if (this.items.length == 0) {
this.items.push(item)
} else {
var add = false;
for (var i = 0; i < this.items.length; i++) {
if (item.pro < this.items[i].pro) {
this.items.splice(i, 0, item)
add = true;
break
}
}
if (!add) {
this.items.push(item)
}
}
}
}