javascript構造一個Stack數據結構

stack的第一種含義是一組數據的存放方式,特點為LIFO,即后進先出(Last in, first out)。
分析stack的特點:

  • push:在最頂層加入數據。
  • pop:返回并移除最頂層的數據。
  • top:返回最頂層數據的值,但不移除它。
/**
 * @file Stack.js
 * @desc 用js實現stack數據結構
 *
 * *************************
 * 用法:
 *  var stack = new Stack();
 *  stack.push([1,2,3]);
 *  stack.push('xxxxx');
 *  var all = stack.displayAll();
 *  console.log(all);
 *
 * *************************
 */

function Stack() {

    // 返回最后插入的一個數據
    this.top = null;

    // 返回棧內數據的長度
    this.size = 0;
}

Stack.prototype = {
    constructor: Stack,

    // 插入一個數據,放在棧的最后一個位置
    push: function (data) {
        var node = {
            data: data,
            next: null
        };
        node.next = this.top;
        this.top = node;
        this.size++;
    },

    // 返回最后的一個數據
    peek: function () {
        return this.top === null ? null : this.top.data;
    },

    // 從棧里取出最后的一個數據,與peek的區別:peek只讀取,pop返回并移除最頂層的數據
    pop: function () {
        if (this.top === null) return null;
        var out = this.top;
        this.top = this.top.next;
        if (this.size > 0) this.size--;
        return out.data;
    },

    // 清楚棧內的數據
    clear: function () {
        this.top = null;
        this.size = 0;
    },

    // 顯示站內的所有數據
    displayAll: function () {
        if (this.top === null) return null;
        var arr = [];
        var current = this.top;
        for (var i = 0, len = this.size; i < len; i++) {
            arr[i] = current.data;
            current = current.next;
        }
        return arr;
    }
};


最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • 聲明:算法和數據結構的文章均是作者從github上翻譯過來,為方便大家閱讀。如果英語閱讀能力強的朋友,可以直接到s...
    UnsanYL閱讀 1,567評論 0 2
  • 第5章 引用類型(返回首頁) 本章內容 使用對象 創建并操作數組 理解基本的JavaScript類型 使用基本類型...
    大學一百閱讀 3,268評論 0 4
  • 1. Java基礎部分 基礎部分的順序:基本語法,類相關的語法,內部類的語法,繼承相關的語法,異常的語法,線程的語...
    子非魚_t_閱讀 31,754評論 18 399
  • 嘿,同學,你好! 那是我們的第一句話。 多年以后的我們分布在城市兩端,你在北方流浪,而我卻不在南方等你回來...
    暖暖瓦力愛伊娃閱讀 451評論 0 1
  • 今天幾乎一整天都在看孩子做家務,真心沒時間學習。但是不甘心啊,所以斷斷續續完成421-500的圓周率數值繪圖。 昨...
    世界記憶大師程程閱讀 694評論 0 0