日韩黑丝制服一区视频播放|日韩欧美人妻丝袜视频在线观看|九九影院一级蜜桃|亚洲中文在线导航|青草草视频在线观看|婷婷五月色伊人网站|日本一区二区在线|国产AV一二三四区毛片|正在播放久草视频|亚洲色图精品一区

分享

JS 數據結構與算法_棧 & 隊列

 板橋胡同37號 2019-11-19

作者:同夢奇緣

https://segmentfault.com/a/1190000017905515

寫在前面

原計劃是把《你不知道的Javascript》三部全部看完的,偶然間朋友推薦了數據結構與算法的一套入門視頻,學之。發(fā)現數據結構并沒有想象中那么遙不可及,反而發(fā)覺挺有意思的。手頭上恰好有《學習Javascript數據結構與算法》的書籍,便轉而先把數據結構與算法學習。

一、認識數據結構

什么是數據結構?下面是維基百科的解釋:

數據結構是計算機存儲、組織數據的方式。數據結構意味著接口或封裝:一個數據結構可被視為兩個函數之間的接口,或者是由數據類型聯合組成的存儲內容的訪問方法封裝

我們每天的編碼中都會用到數據結構,因為數組是最簡單的內存數據結構,下面是常見的數據結構:

  • 數組(Array)

  • 棧(Stack)

  • 隊列(Queue)

  • 鏈表(Linked List)

  • 樹(Tree)

  • 圖(Graph)

  • 堆(Heap)

  • 散列表(Hash)

下面來學習學習棧和隊列。

二、棧

2.1 棧數據結構

棧是一種遵循后進先出(LIFO)原則的有序集合。新添加的或待刪除的元素都保存在棧的同一端,稱作棧頂,另一端就叫棧底。在棧里,新元素都接近棧頂,舊元素都接近棧底。

類比生活中的物件:一摞書??或者推放在一起的盤子。

2.2 棧的實現

普通的棧常用的有以下幾個方法:

  • push 添加一個(或幾個)新元素到棧頂

  • pop 溢出棧頂元素,同時返回被移除的元素

  • peek 返回棧頂元素,不對棧做修改

  • isEmpty 棧內無元素返回 true,否則返回 false

  • size 返回棧內元素個數

  • clear 清空棧

  1. class Stack {

  2.  constructor() {

  3.    this._items = []; // 儲存數據

  4.  }

  5.  // 向棧內壓入一個元素

  6.  push(item) {

  7.    this._items.push(item);

  8.  }

  9.  // 把棧頂元素彈出

  10.  pop() {

  11.    return this._items.pop();

  12.  }

  13.  // 返回棧頂元素

  14.  peek() {

  15.    return this._items[this._items.length - 1];

  16.  }

  17.  // 判斷棧是否為空

  18.  isEmpty() {

  19.    return !this._items.length;

  20.  }

  21.  // 棧元素個數

  22.  size() {

  23.    return this._items.length;

  24.  }

  25.  // 清空棧

  26.  clear() {

  27.    this._items = [];

  28.  }

  29. }

現在再回頭想想數據結構里面的棧是什么。

突然發(fā)現并沒有那么神奇,僅僅只是對原有數據進行了一次封裝而已。而封裝的結果是:并不去關心其內部的元素是什么,只是去操作棧頂元素,這樣的話,在編碼中會更可控一些。

2.3 棧的應用

(1)十進制轉任意進制

要求:給定一個函數,輸入目標數值和進制基數,輸出對應的進制數(最大為16進制)。

  1. baseConverter(10, 2) ==> 1010

  2. baseConverter(30, 16) ==> 1E

分析:進制轉換的本質——將目標值一次一次除以進制基數,得到的取整值為新目標值,記錄下余數,直到目標值小于0,最后將余數逆序組合即可。利用棧,記錄余數入棧,組合時出棧。

  1. // 進制轉換

  2. function baseConverter(delNumber, base) {

  3.  const stack = new Stack();

  4.  let rem = null;

  5.  let ret = [];

  6.  // 十六進制中需要依次對應A~F

  7.  const digits = '0123456789ABCDEF';

  8.  while (delNumber > 0) {

  9.    rem = Math.floor(delNumber % base);

  10.    stack.push(rem);

  11.    delNumber = Math.floor(delNumber / base);

  12.  }

  13.  while (!stack.isEmpty()) {

  14.    ret.push(digits[stack.pop()]);

  15.  }

  16.  return ret.join('');

  17. }

  18. console.log(baseConverter(100345, 2)); //輸出11000011111111001

  19. console.log(baseConverter(100345, 8)); //輸出303771

  20. console.log(baseConverter(100345, 16)); //輸出187F9

(2)逆波蘭表達式計算

要求: 逆波蘭表達式,也叫后綴表達式,它將復雜表達式轉換為可以依靠簡單的操作得到計算結果的表達式,例如 (a+b)*(c+d)轉換為 a b+c d+*

  1. ['4', '13', '5', '/', '+'] ==> (4 + (13 / 5)) = 6

  2. ['10', '6', '9', '3', '+', '-11', '*', '/', '*', '17', '+', '5', '+']

  3. ==> ((10 * (6 / ((9 + 3) * -11))) + 17) + 5

分析: 以符號為觸發(fā)節(jié)點,一旦遇到符號,就將符號前兩個元素按照該符號運算,并將新的結果入棧,直到棧內僅一個元素

  1. function isOperator(str) {

  2.  return ['+', '-', '*', '/'].includes(str);

  3. }

  4. // 逆波蘭表達式計算

  5. function clacExp(exp) {

  6.  const stack = new Stack();

  7.  for (let i = 0; i < exp.length; i++) {

  8.    const one = exp[i];

  9.    if (isOperator(one)) {

  10.      const operatNum1 = stack.pop();

  11.      const operatNum2 = stack.pop();

  12.      const expStr = `${operatNum2}${one}${operatNum1}`;

  13.      const res = eval(expStr);

  14.      stack.push(res);

  15.    } else {

  16.      stack.push(one);

  17.    }

  18.  }

  19.  return stack.peek();

  20. }

  21. console.log(clacExp(['4', '13', '5', '/', '+'])); // 6.6

(3)利用普通棧實現一個有 min方法的棧

思路: 使用兩個棧來存儲數據,其中一個命名為 dataStack,專門用來存儲數據,另一個命名為 minStack,專門用來存儲棧里最小的數據。始終保持兩個棧中的元素個數相同,壓棧時判別壓入的元素與 minStack棧頂元素比較大小,如果比棧頂元素小,則直接入棧,否則復制棧頂元素入棧;彈出棧頂時,兩者均彈出即可。這樣 minStack的棧頂元素始終為最小值。

  1. class MinStack {

  2.  constructor() {

  3.    this._dataStack = new Stack();

  4.    this._minStack = new Stack();

  5.  }

  6.  push(item) {

  7.    this._dataStack.push(item);

  8.    // 為空或入棧元素小于棧頂元素,直接壓入該元素

  9.    if (this._minStack.isEmpty() || this._minStack.peek() > item) {

  10.      this._minStack.push(item);

  11.    } else {

  12.      this._minStack.push(this._minStack.peek());

  13.    }

  14.  }

  15.  pop() {

  16.    this._dataStack.pop();

  17.    return this._minStack.pop();

  18.  }

  19.  min() {

  20.    return this._minStack.peek();

  21.  }

  22. }

  23. const minstack = new MinStack();

  24. minstack.push(3);

  25. minstack.push(4);

  26. minstack.push(8);

  27. console.log(minstack.min()); // 3

  28. minstack.push(2);

  29. console.log(minstack.min()); // 2

三、隊列

3.1 隊列數據結構

隊列是遵循先進先出(FIFO,也稱為先來先服務)原則的一組有序的項。隊列在尾部添加新元素,并從頂部移除元素。最新添加的元素必須排在隊列的末尾。

類比:日常生活中的購物排隊。

3.2 隊列的實現

普通的隊列常用的有以下幾個方法:

  • enqueue 向隊列尾部添加一個(或多個)新的項

  • dequeue 移除隊列的第一(即排在隊列最前面的)項,并返回被移除的元素

  • head 返回隊列第一個元素,隊列不做任何變動

  • tail 返回隊列最后一個元素,隊列不做任何變動

  • isEmpty 隊列內無元素返回 true,否則返回 false

  • size 返回隊列內元素個數

  • clear 清空隊列

  1. class Queue {

  2.  constructor() {

  3.    this._items = [];

  4.  }

  5.  enqueue(item) {

  6.    this._items.push(item);

  7.  }

  8.  dequeue() {

  9.    return this._items.shift();

  10.  }

  11.  head() {

  12.    return this._items[0];

  13.  }

  14.  tail() {

  15.    return this._items[this._items.length - 1];

  16.  }

  17.  isEmpty() {

  18.    return !this._items.length;

  19.  }

  20.  size() {

  21.    return this._items.length;

  22.  }

  23.  clear() {

  24.    this._items = [];

  25.  }

  26. }

與棧類比,棧僅能操作其頭部,隊列則首尾均能操作,但僅能在頭部出尾部進。當然,也印證了上面的話:棧和隊列并不關心其內部元素細節(jié),也無法直接操作非首尾元素。

3.3 隊列的應用

(1)約瑟夫環(huán)(普通模式)

要求: 有一個數組 a[100]存放0~99;要求每隔兩個數刪掉一個數,到末尾時循環(huán)至開頭繼續(xù)進行,求最后一個被刪掉的數。

分析: 按數組創(chuàng)建隊列,依次判斷元素是否滿足為指定位置的數,如果不是則 enqueue到尾部,否則忽略,當僅有一個元素時便輸出。

  1. // 創(chuàng)建一個長度為100的數組

  2. const arr_100 = Array.from({ length: 100 }, (_, i) => i*i);

  3. function delRing(list) {

  4.  const queue = new Queue();

  5.  list.forEach(e => { queue.enqueue(e); });

  6.  let index = 0;

  7.  while (queue.size() !== 1) {

  8.    const item = queue.dequeue();

  9.    index += 1;

  10.    if (index % 3 !== 0) {

  11.      queue.enqueue(item);

  12.    }

  13.  }

  14.  return queue.tail();

  15. }

  16. console.log(delRing(arr_100)); // 8100 此時index=297

(2)菲波那切數列(普通模式)

要求: 使用隊列計算斐波那契數列的第n項。

分析: 斐波那契數列的前兩項固定為1,后面的項為前兩項之和,依次向后,這便是斐波那契數列。

  1. function fibonacci(n) {

  2.    const queue = new Queue();

  3.    queue.enqueue(1);

  4.    queue.enqueue(1);

  5.    let index = 0;

  6.    while(index < n - 2) {

  7.        index += 1;

  8.        // 出隊列一個元素

  9.        const delItem = queue.dequeue();

  10.        // 獲取頭部值

  11.        const headItem = queue.head();

  12.        const nextItem = delItem + headItem;

  13.        queue.enqueue(nextItem);

  14.    }

  15.    return queue.tail();

  16. }

  17. console.log(fibonacci(9)); // 34

(3)用隊列實現一個棧

要求: 用兩個隊列實現一個棧。

分析: 使用隊列實現棧最主要的是在隊列中找到棧頂元素并對其操作。具體的思路如下:

  1. 兩個隊列,一個備份隊列 emptyQueue,一個是數據隊列 dataQueue;

  2. 在確認棧頂時,依次 dequeue至備份隊列,置換備份隊列和數據隊列的引用即可。

  1. class QueueStack {

  2.  constructor() {

  3.    this.queue_1 = new Queue();

  4.    this.queue_2 = new Queue();

  5.    this._dataQueue = null; // 放數據的隊列

  6.    this._emptyQueue = null; // 空隊列,備份使用

  7.  }

  8.  // 確認哪個隊列放數據,哪個隊列做備份空隊列

  9.  _initQueue() {

  10.    if (this.queue_1.isEmpty() && this.queue_2.isEmpty()) {

  11.      this._dataQueue = this.queue_1;

  12.      this._emptyQueue = this.queue_2;

  13.    } else if (this.queue_1.isEmpty()) {

  14.      this._dataQueue = this.queue_2;

  15.      this._emptyQueue = this.queue_1;

  16.    } else {

  17.      this._dataQueue = this.queue_1;

  18.      this._emptyQueue = this.queue_2;

  19.    }

  20.  };

  21.  push(item) {

  22.    this.init_queue();

  23.    this._dataQueue.enqueue(item);

  24.  };

  25.  peek() {

  26.    this.init_queue();

  27.    return this._dataQueue.tail();

  28.  }

  29.  pop() {

  30.    this.init_queue();

  31.    while (this._dataQueue.size() > 1) {

  32.      this._emptyQueue.enqueue(this._dataQueue.dequeue());

  33.    }

  34.    return this._dataQueue.dequeue();

  35.  };

  36. };

同樣的,一個隊列也能實現棧的基本功能:

  1. class QueueStack {

  2.  constructor() {

  3.    this.queue = new Queue();

  4.  }

  5.  push(item) {

  6.    this.queue.enqueue(item);

  7.  }

  8.  pop() {

  9.    // 向隊列末尾追加 隊列長度-1 次,后彈出隊列頭部

  10.    for(let i = 1; i < this.queue.size(); i += 1) {

  11.      this.queue.enqueue(this.queue.dequeue());

  12.    }

  13.    return this.queue.dequeue();

  14.  }

  15.  peek() {

  16.    return this.queue.tail();

  17.  }

  18. }

學習了棧和隊列這類簡單的數據結構,我們會發(fā)現。數據結構并沒有之前想象中那么神秘,它們只是規(guī)定了這類數據結構的操作方式:棧只能對棧頂進行操作,隊列只能在尾部添加在頭部彈出;且它們不關心內部的元素狀態(tài)。

個人認為,學習數據結構是為了提高我們通過代碼建模的能力,這也是任何一門編程語言都通用的知識體系,優(yōu)秀編碼者必學之。


  • 分享前端好文,缺個 在看 

    本站是提供個人知識管理的網絡存儲空間,所有內容均由用戶發(fā)布,不代表本站觀點。請注意甄別內容中的聯系方式、誘導購買等信息,謹防詐騙。如發(fā)現有害或侵權內容,請點擊一鍵舉報。
    轉藏 分享 獻花(0

    0條評論

    發(fā)表

    請遵守用戶 評論公約

    類似文章 更多