javascript數據結構與算法-棧

定義

棧做爲一種數據結構,是一種只能在一端進行插入和刪除操做的特殊線性表。它按照先進後出的原則存儲數據,先進入的數據被壓入棧底,最後的數據在棧頂,須要讀數據的時候從棧頂開始彈出數據(最後一個數據被第一個讀出來)。棧具備記憶做用,對棧的插入與刪除操做中,不須要改變棧底指針。 棧是容許在同一端進行插入和刪除操做的特殊線性表。容許進行插入和刪除操做的一端稱爲棧頂(top),另外一端爲棧底(bottom);棧底固定,而棧頂浮動;棧中元素個數爲零時稱爲空棧。插入通常稱爲進棧(PUSH),刪除則稱爲退棧(POP)。棧也稱爲後進先出表。es6

方法和屬性

  • push方法 入棧
  • pop方法 刪除棧頂的元素
  • peek方法 查看當前棧頂的元素
  • isEmpty方法
  • size方法
  • toString方法 打印出全部元素
  • length屬性 棧的元素個數
  • list屬性 存儲棧
    下面是出棧和入棧的示意圖,照片來自網絡

代碼實現棧

這裏咱們用js數組來模擬棧,應爲js是一門強大的高級語言,數組的push和pop方法在棧中也一樣適用數組

class Stack {
  constructor() {
    this.list = [];
    this.length = 0;
  }
  push(value) {
    this.length++;
    this.list.push(value);
  }
  pop() {
    if (this.isEmpty()) {
      return undefined;
    }
    this.length--;
    return this.list.pop();
  }
  isEmpty() {
    return this.length === 0;   
  }
  size() {
    return this.length;
  }
  peek() {
    if (this.isEmpty()) {
      return undefined;
    }
    return this.list[this.length - 1];
  }
  toString() {
    if (this.isEmpty()) {
      return '';
    }
    let objString = `${this.list[0]}`;
    for (let i = 1; i < this.length; i++) {
      objString = `${objString},${this.list[i]}`;
    }
    return objString;
  }
}
複製代碼

或者用對象來實現棧,可是沒有數組原生的那些函數了

入棧的時候,索引會變成對象的下標,就能set和get了bash

class Stack {
  constructor() {
    this.length = 0;
    this.items = {};
  }
  push(element) {
    this.items[this.length] = element;
    this.length++;
  }
  pop() {
    if (this.isEmpty()) {
      return undefined;
    }
    this.length--;
    const result = this.items[this.length];
    delete this.items[this.length];
    return result;
  }
  peek() {
    if (this.isEmpty()) {
      return undefined;
    }
    return this.items[this.length - 1];
  }
  isEmpty() {
    return this.length === 0;
  }
  size() {
    return this.length;
  }
  clear() {
    /* while (!this.isEmpty()) {
        this.pop();
      } */
    this.items = {};
    this.length = 0;
  }
  toString() {
    if (this.isEmpty()) {
      return '';
    }
    let objString = `${this.items[0]}`;
    for (let i = 1; i < this.length; i++) {
      objString = `${objString},${this.items[i]}`;
    }
    return objString;
  }
}
複製代碼

用ts實現一遍

class Stack<T> {
  private count: number;
  private items: any;

  constructor() {
    this.count = 0;
    this.items = {};
  }

  push(element: T) {
    this.items[this.count] = element;
    this.count++;
  }

  pop() {
    if (this.isEmpty()) {
      return undefined;
    }
    this.count--;
    const result = this.items[this.count];
    delete this.items[this.count];
    return result;
  }

  peek() {
    if (this.isEmpty()) {
      return undefined;
    }
    return this.items[this.count - 1];
  }

  isEmpty() {
    return this.count === 0;
  }

  size() {
    return this.count;
  }

  clear() {
    /* while (!this.isEmpty()) {
      this.pop();
    } */

    this.items = {};
    this.count = 0;
  }
  toString() {
    if (this.isEmpty()) {
      return '';
    }
    let objString = `${this.items[0]}`;
    for (let i = 1; i < this.count; i++) {
      objString = `${objString},${this.items[i]}`;
    }
    return objString;
  }
}
複製代碼

存在的問題

儘管代碼看起來還行,可是咱們發現list時公用的,es6貌似不能聲明私有變量和私有函數,畢竟別的語言的 private 太強大了,網上有不少種實現形式,目前比較讓人承認的,主要是weakmap和symbol兩種,但我以爲這樣寫代碼也太不優雅了,先公共着吧,hhhhh網絡

用棧實現10進制向n進制轉換

咱們知道二進制是除2取餘再從下往上拿餘數,取餘數是%,從下往上拿餘數和從循環棧頂拿元素類似。同理轉8 進制就是除8取餘.... 實現思路:數據結構

  • 最高位爲 num % base 而後直接壓入棧;
  • 使用 num / base 來代替 num ;
  • 重複上面的步驟,直到 n 爲 0 ,而且沒有餘數;
  • 以此將棧內元素彈出,直到棧空,並依次將這些元素排列,就獲得了轉換後的形式
let mulBase =(num,base)=>{
    let s = new Stack();
    while(num>0){
        s.push(num%base);
        num = Math.floor(num/=base);
    }
    var converted = "";
    while(s.size()>0){
        converted+=s.pop();
    }
    return converted;
} 
複製代碼

用棧實現迴文判斷

實現思路:將字符串的每一次一次入棧,探後循環出棧,判斷出棧後的字符串和原來的字符串是不是相等的,若一致,則是迴文函數

let isPalindrome=(str)=>{
    let s = new Stack();
    for(let i = 0;i<str.length;i++){
        // 依次入棧
        s.push(str[i]);
    }
    let newStr = "";
    while(s.size()>0){
        newStr+=s.pop();
    }
    if(newStr===str){
        return true;
    }else{
        return false;
    }
}
console.log(isPalindrome("123321")) // true
複製代碼

另外一種方法字符串直接翻轉就行了ui

let isPalindrome =( word )=>{
    return String(word).split('').reverse().join('') == word ? true : false;
}
複製代碼
相關文章
相關標籤/搜索