8種常見數據結構及其Javascript實現web

做前端的同學不少都是自學成才或者半路出家,計算機基礎的知識比較薄弱,尤其是數據結構和算法這塊,所以今天整理了一下常見的數據結構和對應的Javascript的實現,希望能幫助大家完善這方面的知識體系。

1. Stack(棧)

Stack的特點是後進先出(last in first out)。生活中常見的Stack的例子比如一摞書,你最後放上去的那本你之後會最先拿走;又比如瀏覽器的訪問歷史,當點擊返回按鈕,最後訪問的網站最先從歷史記錄中彈出。

Stack一般具備以下方法:

push:將一個元素推入棧頂

pop:移除棧頂元素,並返回被移除的元素

peek:返回棧頂元素

length:返回棧中元素的個數

Javascript的Array天生具備了Stack的特性,但我們也可以從頭實現一個 Stack類:function Stack() {

this.count = 0;

this.storage = {};

this.push = function (value) {

this.storage[this.count] = value;

this.count++;

}

this.pop = function () {

if (this.count === 0) {

return undefined;

}

this.count--;

var result = this.storage[this.count];

delete this.storage[this.count];

return result;

}

this.peek = function () {

return this.storage[this.count - 1];

}

this.size = function () {

return this.count;

}

}

xiaowanzi02620


分享到:


相關文章: