前言
最近在看数据结构和算法的书,《学习JavaScript数据结构和算法》。记录一下一些感兴趣的算法
一、栈
栈是先进后出的原则
function Stack(){
let items = []
this.push = function(e){
items.push(e)
}
this.pop = function(){
return items.pop()
}
this.peek = function(){
return items[items.length-1]
}
this.isEmpty = function(){
return items.length == 0
}
this.size = function(){
return items.length
}
this.clear = function(){
items = []
}
}
function baseConverter(decNumber,base){
var remStack = new Stack(),
rem,
baseString = '',
digite = '0123456789ABCDEF';
while(decNumber > 0){
rem = Math.floor(decNumber % base);
remStack.push(rem);
decName=Math.floor(decNumber / base)
}
while(!remStack.isEmpty()){
baseString += digite[remStrack.pop()]
}
return baseString
}
二、队列
队列是先进先出的原则
function Queue(){
let items = []
this.enqueue=function(e){
items.push(e)
}
this.dequeue=function(){
items.shift()
}
this.front=function(){
return items[0]
}
this.isEmpty=function(){
return items.length == 0
}
this.size=function(){
return items.length
}
}
function PriorityQueue(){
let items = []
function QueueElement(element,priority){
this.element = element
this.priority = priority
}
this.enqueue = function(e,p){
let queueElement = new QueueElement(e,p)
if(this.isEmpty()){
items.push(queueElement)
}else{
let added = false
if(let i=0;i<items.length;i++){
if(queueElement.priority < items[i].priority){
items.splice(i,0,queueElement)
added = true
break
}
})
if(!added){
items.push(queueElement)
}
}
}
}
function hotPatato(nameList,num){
let queue = new Queue()
nameList.map(i => queue.enqueue(nameList[i]))
let eliminated = ''
while(queue.size() > 1){
for(let i=0;i<num;i++){
queue.enqueue(queue.dequeue())
}
eliminated = queue.dequeue()
console.log(`${eliminated}在击鼓传花游戏中淘汰`)
}
return queue.dequeue()
}
|