天天看點

對資料結構的研究 隊列、棧的研究

隊列 

      這個很好了解 先入先出,有點像排隊,通過數組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('{{(({}))}}'))