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

队列 

      这个很好理解 先入先出,有点像排队,通过数组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('{{(({}))}}'))


原文地址:https://www.cnblogs.com/zhouyideboke/p/12964292.html