javascript完成數據構造中的棧構造

在javascript中,一些應用底本數組沒法隨意馬虎處理的題目,實在也是能夠經由過程模仿數據組織來處理題目的,並非是說前端就不須要去學數據組織與算法,曉得數據組織的前端才是真的程序員。

下面簡樸地用javascript來完成數據組織中的棧組織,棧組織的先入后出性子在處理某些數據題目時很有效

  • 棧的組織函數
function Stack() {
    this.dataStore = [];
    this.top = 0;
    this.push = push;
    this.pop = pop;
    this.peek = peek;
    this.clear = clear;
    this.length = length;
}
  • 從棧頂放入某個元素
function push(element) {
    this.dataStore[this.top++] = element;
}
  • 從棧頂掏出某個元素
function pop() {
    return this.dataStore[--this.top]
}
  • 取得棧的高度
function length() {
    return this.top;
}

  • 清空全部棧
function clear() {
    this.top = 0;
}
  • 轉變棧頂的位置
function peek() {
   return this.dataStore[this.top - 1];
}

下面是一個風趣的例子 應用stack類完成10進制轉換為別的進制


function mulBase(num, base) {
    let s = new Stack();
    do {
        s.push(num % base);
        num = Math.floor(num /= base);
    } while (num > 0);
    let content = '';
    while (s.length() > 0) {
        content += s.pop();
    }
    return content;
}

將10進制數9轉換為2進制數1001 print(mulBase(9, 2));

又是一個風趣的例子,用棧來推斷是不是是迴文,迴文就是一個字符串,夙昔今後寫扈從后往前寫都是一樣的 比方’racecar’,’data’

function isPalindrome(word) {
        let s = new Stack();
        for (let i = 0; i < word.length; i++) {
            s.push(word[i]);
        }
        let rword = '';
        while (s.length() > 0) {
            rword += s.pop();
        }
        if (word == rword) {
            return true;
        } else {
            return false;
        }
    }

推斷racecar是不是是迴文 print(isPalindrome(‘racecar’));用棧能夠完成許多輕易的功用,能夠見得前端相識數據組織尤為重要。

迎接批評以及留言,同時迎接關注我的博客定時不斷地更新我的文章 陳建光的博客

    原文作者:陳建光
    原文地址: https://segmentfault.com/a/1190000014442537
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞