乡下人产国偷v产偷v自拍,国产午夜片在线观看,婷婷成人亚洲综合国产麻豆,久久综合给合久久狠狠狠9

  • <output id="e9wm2"></output>
    <s id="e9wm2"><nobr id="e9wm2"><ins id="e9wm2"></ins></nobr></s>

    • 分享

      JS 數(shù)據(jù)結(jié)構(gòu)與算法_棧 & 隊列

       板橋胡同37號 2019-11-19

      作者:同夢奇緣

      https://segmentfault.com/a/1190000017905515

      寫在前面

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

      一、認(rèn)識數(shù)據(jù)結(jié)構(gòu)

      什么是數(shù)據(jù)結(jié)構(gòu)?下面是維基百科的解釋:

      數(shù)據(jù)結(jié)構(gòu)是計算機(jī)存儲、組織數(shù)據(jù)的方式。數(shù)據(jù)結(jié)構(gòu)意味著接口或封裝:一個數(shù)據(jù)結(jié)構(gòu)可被視為兩個函數(shù)之間的接口,或者是由數(shù)據(jù)類型聯(lián)合組成的存儲內(nèi)容的訪問方法封裝

      我們每天的編碼中都會用到數(shù)據(jù)結(jié)構(gòu),因為數(shù)組是最簡單的內(nèi)存數(shù)據(jù)結(jié)構(gòu),下面是常見的數(shù)據(jù)結(jié)構(gòu):

      • 數(shù)組(Array)

      • 棧(Stack)

      • 隊列(Queue)

      • 鏈表(Linked List)

      • 樹(Tree)

      • 圖(Graph)

      • 堆(Heap)

      • 散列表(Hash)

      下面來學(xué)習(xí)學(xué)習(xí)棧和隊列。

      二、棧

      2.1 棧數(shù)據(jù)結(jié)構(gòu)

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

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

      2.2 棧的實現(xiàn)

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

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

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

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

      • isEmpty 棧內(nèi)無元素返回 true,否則返回 false

      • size 返回棧內(nèi)元素個數(shù)

      • clear 清空棧

      1. class Stack {

      2.  constructor() {

      3.    this._items = []; // 儲存數(shù)據(jù)

      4.  }

      5.  // 向棧內(nèi)壓入一個元素

      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.  // 棧元素個數(shù)

      22.  size() {

      23.    return this._items.length;

      24.  }

      25.  // 清空棧

      26.  clear() {

      27.    this._items = [];

      28.  }

      29. }

      現(xiàn)在再回頭想想數(shù)據(jù)結(jié)構(gòu)里面的棧是什么。

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

      2.3 棧的應(yīng)用

      (1)十進(jìn)制轉(zhuǎn)任意進(jìn)制

      要求:給定一個函數(shù),輸入目標(biāo)數(shù)值和進(jìn)制基數(shù),輸出對應(yīng)的進(jìn)制數(shù)(最大為16進(jìn)制)。

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

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

      分析:進(jìn)制轉(zhuǎn)換的本質(zhì)——將目標(biāo)值一次一次除以進(jìn)制基數(shù),得到的取整值為新目標(biāo)值,記錄下余數(shù),直到目標(biāo)值小于0,最后將余數(shù)逆序組合即可。利用棧,記錄余數(shù)入棧,組合時出棧。

      1. // 進(jìn)制轉(zhuǎn)換

      2. function baseConverter(delNumber, base) {

      3.  const stack = new Stack();

      4.  let rem = null;

      5.  let ret = [];

      6.  // 十六進(jìn)制中需要依次對應(yīng)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)逆波蘭表達(dá)式計算

      要求: 逆波蘭表達(dá)式,也叫后綴表達(dá)式,它將復(fù)雜表達(dá)式轉(zhuǎn)換為可以依靠簡單的操作得到計算結(jié)果的表達(dá)式,例如 (a+b)*(c+d)轉(zhuǎn)換為 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é)點,一旦遇到符號,就將符號前兩個元素按照該符號運算,并將新的結(jié)果入棧,直到棧內(nèi)僅一個元素

      1. function isOperator(str) {

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

      3. }

      4. // 逆波蘭表達(dá)式計算

      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)利用普通棧實現(xiàn)一個有 min方法的棧

      思路: 使用兩個棧來存儲數(shù)據(jù),其中一個命名為 dataStack,專門用來存儲數(shù)據(jù),另一個命名為 minStack,專門用來存儲棧里最小的數(shù)據(jù)。始終保持兩個棧中的元素個數(shù)相同,壓棧時判別壓入的元素與 minStack棧頂元素比較大小,如果比棧頂元素小,則直接入棧,否則復(fù)制棧頂元素入棧;彈出棧頂時,兩者均彈出即可。這樣 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 隊列數(shù)據(jù)結(jié)構(gòu)

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

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

      3.2 隊列的實現(xiàn)

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

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

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

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

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

      • isEmpty 隊列內(nèi)無元素返回 true,否則返回 false

      • size 返回隊列內(nèi)元素個數(shù)

      • 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. }

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

      3.3 隊列的應(yīng)用

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

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

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

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

      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)菲波那切數(shù)列(普通模式)

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

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

      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)用隊列實現(xiàn)一個棧

      要求: 用兩個隊列實現(xiàn)一個棧。

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

      1. 兩個隊列,一個備份隊列 emptyQueue,一個是數(shù)據(jù)隊列 dataQueue;

      2. 在確認(rèn)棧頂時,依次 dequeue至備份隊列,置換備份隊列和數(shù)據(jù)隊列的引用即可。

      1. class QueueStack {

      2.  constructor() {

      3.    this.queue_1 = new Queue();

      4.    this.queue_2 = new Queue();

      5.    this._dataQueue = null; // 放數(shù)據(jù)的隊列

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

      7.  }

      8.  // 確認(rèn)哪個隊列放數(shù)據(jù),哪個隊列做備份空隊列

      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. };

      同樣的,一個隊列也能實現(xiàn)棧的基本功能:

      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. }

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

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


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

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

        0條評論

        發(fā)表

        請遵守用戶 評論公約

        類似文章 更多