官术网_书友最值得收藏!

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.
主站蜘蛛池模板: 娄底市| 襄樊市| 新安县| 亳州市| 鄱阳县| 新营市| 凤翔县| 隆化县| 沁源县| 日喀则市| 郓城县| 安国市| 乌兰县| 彰化县| 离岛区| 前郭尔| 高雄县| 枣阳市| 潮州市| 巴青县| 宣威市| 拜城县| 瑞丽市| 论坛| 靖江市| 雷山县| 沙湾县| 昔阳县| 英山县| 永城市| 通化县| 郓城县| 买车| 黑山县| 西城区| 东宁县| 穆棱市| 通许县| 鱼台县| 津南区| 南平市|