包工頭帶你通算法--js 描述 棧 隊列(一)

包工頭帶你通算法--js 描述 棧,隊列(一)

簡單敘述下棧 隊列

  1. 棧:先進後出 ,隊列:先進先出(就是這麼簡單)。個人理解, 棧就是給個數組a = [1,2,3,4] 只能進行pop(), 和push()操作, 隊列就是隻能進行shift() push()操作
  2. talk is cheap show me the picture(左棧 右隊列)

clipboard.png

這是書上的棧,隊列

感覺怪怪的
clipboard.png
clipboard.png

都9012年了

    class Stack{
        constructor(){
            this.data = [];
            this.top = 0;
            this.length = 0;
        }
         // 入棧
        push(ele){
            this.length ++;
            return this.data[this.top ++] = ele;
        }
        // 出棧
        pop(){
            this.top > 0 ? this.top -- : false;
            this.length > 0 ? this.length -- : false;
            return this.data.pop();
        }
        // 清空棧
        clear(){
            this.top = 0;
            this.length = 0;
            return this.data = [];
        }
        // 返回棧頂元素
        posTop(){
            return this.data[-- this.top]; // 這裏要先減 再賦值
        }
    }

    var st = new Stack();
  

clipboard.png

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章