javascript構(gòu)造一個(gè)Stack數(shù)據(jù)結(jié)構(gòu)

stack的第一種含義是一組數(shù)據(jù)的存放方式,特點(diǎn)為L(zhǎng)IFO,即后進(jìn)先出(Last in, first out)。
分析stack的特點(diǎn):

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

function Stack() {

    // 返回最后插入的一個(gè)數(shù)據(jù)
    this.top = null;

    // 返回棧內(nèi)數(shù)據(jù)的長(zhǎng)度
    this.size = 0;
}

Stack.prototype = {
    constructor: Stack,

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

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

    // 從棧里取出最后的一個(gè)數(shù)據(jù),與peek的區(qū)別:peek只讀取,pop返回并移除最頂層的數(shù)據(jù)
    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;
    },

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

    // 顯示站內(nèi)的所有數(shù)據(jù)
    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;
    }
};


最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

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

友情鏈接更多精彩內(nèi)容