JavaScript數據結構01

最近在回顧一些基礎知識,在目前枝繁葉茂的前端中把基礎知識弄紮實。基礎紮實了上層建築才能牢固。這是一些筆記,雖然是一些簡單的東西,但仍是拿出來與你們分享一下。養成一種分享的習慣。有什麼寫的不對的地方,請直接指出。javascript

列表

列表是一組有序的數據。每一個列表中的數據項稱爲元素。在JavaScript中,列表中的元素能夠是任意數據類型。前端

場景

當列表中保存的元素很少時;不須要很長的序列中查找元素;不須要對齊進行排序。java

若是數據結構很是複雜,列表的做用就沒那麼大了。例如人們常常使用的待辦事項列表、購物清單、流行榜單等就很合適使用。數據結構

實現簡單的列表類

/** * List * @constructor */
function List() {

    // 初始化數據
    this.data = [];
    // 添加
    this.add = function (item){};
    // 刪除
    this.remove = function (id){};
    // 查找
    this.find = function (id){};
    // 清空
    this.clear = function () {};
    // 獲取列表數據
    this.getData = function (){};

}

var ins = new List();複製代碼

棧是一種特殊的列表,棧內的元素只能經過一端訪問,這一端稱爲棧頂。棧是後入先出的數據結構。ui

因爲棧具備後入先出的特色,因此任何不在棧頂的元素都沒法訪問。爲了獲得棧頂的元素,必須先去掉上面的元素。this

棧的JS實現

function Stack() {
    this.dataStore = [];
    this.top = 0; //棧頂
    this.push = push; // 入棧
    this.pop = pop; // 出棧並刪除
    this.peek = peek; // 出棧單不刪除
    this.clear = clear;
    this.getLength = getLength;
}

function push(el) {
    this.dataStore[this.top++] = el;
}

function pop() {
    return this.dataStore[--this.top];
}

function peek() {
    return this.dataStore[this.top-1];
}

function clear() {
    this.top = 0;
}

function getLength() {
    return this.top;
}

var ins = new Stack();
ins.push('a');
ins.push('b');
ins.push('c');複製代碼

舉2個棧實際應用的栗子

  • 數制間的相互轉換
function mulBase(num, base) {
    var s = new Stack();
    do {
        s.push(num % base);
        num = Math.floor(num /= base);
    } while (num > 0);
    var converted = "";
    while (s.getLength() > 0) {
        converted += s.pop();
    }
    return converted;
}
console.log(mulBase(25,2));// 11001複製代碼
  • 迴文判斷

迴文:一個單詞、短語或者數字,從前日後寫都是同樣的。例如 abba 倒過來仍是abbaspa

function isPalindrome(word) {
    var stack = new Stack(),
        i = 0,
        l = word.length;
    for (; i < l; i++) {
        stack.push(word.charAt(i))
    }
    var rword = "";
    while (stack.getLength() > 0) {
        rword += stack.pop();
    }
    return rword === word;
}
console.log(isPalindrome("rar")) //true
console.log(isPalindrome("test"))//false複製代碼

隊列

隊列是一種列表,不一樣的是隊列只能在隊尾插入元素,在對首刪除元素。隊列用於存儲按順序排列的數據,先進先出。隊列應用比較普遍,提交操做系統執行一些進程,打印任務池,平常排隊買東西等等。操作系統

隊列的JS實現

function Queue() {
    this.dataStore = [];
    this.enqueue = enqueue;
    this.dequeue = dequeue;
    this.front = front;
    this.back = back;
    this.toString = toString;
    this.empty = empty;
}
function enqueue(element) {
    this.dataStore.push(element)
}
function dequeue() {
    this.dataStore.shift()
}
function front() {
    return this.dataStore[0];
}
function back() {
    return this.dataStore[this.dataStore.length - 1];
}
function toString() {
    var str = '',
        i = 0,
        l = this.dataStore.length;
    for ( ; i < l; i++) {
        str += this.dataStore[i] + "\n";
    }
    return str;
}
function empty() {
    return this.dataStore.length === 0;
}
// 實例化
var q = new Queue();
q..enqueue('a');複製代碼
相關文章
相關標籤/搜索