資料結構與演算法JavaScript (一) 棧

來源:互聯網
上載者:User

資料結構與演算法JavaScript (一) 棧
棧結構 特殊的列表,棧內的元素只能通過列表的一端訪問,棧頂 後入先出(LIFO,last-in-first-out)的資料結構   javascript提供可操作的方法, 入棧 push, 出棧 pop,但是pop會移掉棧中的資料 image_thumb2 實現一個棧的實作類別 底層存數資料結構採用 數組 因為pop是刪除棧中資料,所以需要實現一個尋找方法 peek 實現一個清理方法 clear 棧內元素總量尋找 length 尋找是否還存在元素 empty  function Stack(){    this.dataStore = []    this.top    = 0;    this.push   = push    this.pop    = pop    this.peek   = peek    this.length = length;} function push(element){    this.dataStore[this.top++] = element;} function peek(element){    return this.dataStore[this.top-1];} function pop(){    return this.dataStore[--this.top];} function clear(){    this.top = 0} function length(){    return this.top}   迴文 迴文就是指一個單詞,數組,短語,從前往後從後往前都是一樣的 12321.abcba 迴文最簡單的思路就是, 把元素反轉後如果與原始的元素相等,那麼就意味著這就是一個迴文了 這裡可以用到這個棧類來操作  function isPalindrome(word) {    var s = new Stack()    for (var i = 0; i < word.length; i++) {        s.push(word[i])    }    var rword = "";    while (s.length() > 0) {        rword += s.pop();    }    if (word == rword) {        return true;    } else {        return false;    }} isPalindrome("aarra") //falseisPalindrome("aaraa") //true 看看這個isPalindrome函數,其實就是通過調用Stack類,然後把傳遞進來的word這個元素給分解後的每一個組成單元給壓入到棧了,根據棧的原理,後入先出的原則,通過pop的方法在反組裝這個元素,最後比較下之前與組裝後的,如果相等就是迴文了   遞迴 用遞迴實現一個階乘演算法 5! = 5 * 4 * 3 * 2 * 1 = 120 用遞迴  function factorial(n) {    if (n === 0) {        return 1;    } else {        return n * factorial(n - 1);    }} 用棧操作  function fact(n) {    var s = new Stack()    while (n > 1) {        //[5,4,3,2]        s.push(n--);    }    var product = 1;    while (s.length() > 0) {        product *= s.pop();    }    return product;} fact(5) //120 通過while把n = 5 遞減壓入棧,然後再通過一個迴圈還是根據棧的後入先出的原則,通過pop方法把最前面的取出來與product疊加 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.