- Hands-On Data Structures and Algorithms with JavaScript
- Kashyap Mukkamala
- 259字
- 2021-06-30 19:12:07
Don't we have arrays for this?
From what we have seen so far, you might wonder why one would need a stack in the first place. It's very similar to an array, and we can perform all of these operations on an array. Then, what is the real purpose of having a stack?
The reasons for preferring a stack over an array are multifold:
- Using stacks gives a more semantic meaning to your application. Consider this analogy where you have a backpack (an array) and wallet (a stack). Can you put money in both the backpack and wallet? Most certainly; however, when you look at a backpack, you have no clue as to what you may find inside it, but when you look at a wallet, you have a very good idea that it contains money. What kind of money it holds (that is, the data type), such as Dollars, INR, and Pounds, is, however, still not known (supported, unless you take support from TypeScript).
- Native array operations have varying time complexities. Let's take Array.prototype.splice and Array.prototype.push, for example. Splice has a worst-case time complexity of O(n), as it has to search through all the index and readjust it when an element is spliced out of the array. Push has a worst case complexity of O(n) when the memory buffer is full but is amortized O(1). Stacks avoid elements being accessed directly and internally rely on a WeakMap(), which is memory efficient as you will see shortly.
推薦閱讀
- Java EE 6 企業級應用開發教程
- PHP程序設計(慕課版)
- arc42 by Example
- C和C++安全編碼(原書第2版)
- 基于免疫進化的算法及應用研究
- 64位匯編語言的編程藝術
- Java:High-Performance Apps with Java 9
- Web Development with MongoDB and Node(Third Edition)
- Java語言程序設計教程
- Instant Zurb Foundation 4
- 創意UI Photoshop玩轉移動UI設計
- Koa與Node.js開發實戰
- 威脅建模:設計和交付更安全的軟件
- 陪孩子像搭積木一樣學編程:Python真好玩+Scratch趣味編程(全2冊)
- 前端程序員面試筆試通關寶典