对数据结构的研究 队列、栈的研究

 

队列 

      这个很好理解 先入先出,有点像排队,通过数组push和shift模拟,通常用作任务管理

 

// 栈

class Stack{
constructor() {
this.items=[]
}
push(item){
this.items.push(item)
}
pop(){
return this.items.pop()
}
size(){
return this.items.length
}
clear(){
this.items=[]
}
// 索引O(n)
// 搜索O(n)
// 插入O(1)
// 移除O(1)
}

// 经典案例:括号匹配,html标签匹配,表达式计算

function isBalance(symbol) {
const stack=new Stack()
const left="{("
const right="})"
let popValue
let tag=true
const match=function (popValue,current) {
if(left.indexOf(popValue)!==right.indexOf(current)){
tag=false
}
}
for(let i=0;i<symbol.length;i++){
if(left.includes(symbol[i])){
stack.push(symbol[i])
}else if(right.includes(symbol[i])){
popValue=stack.pop()
match(popValue,symbol[i])
}
}
return tag
}
console.log(isBalance('{{(({}))}}'))
console.log(isBalance('{{(({}))}}'))


 

posted @ 2020-05-26 11:10  又回到了起点  阅读(199)  评论(0编辑  收藏  举报