August 2024
Intermediate to advanced
516 pages
11h 47m
English
Most programming languages don’t come with the stack as a built-in data type or class. Instead, it’s up to you to implement it yourself. This is a stark contrast with arrays, which are available in most languages.
To create a stack, then, you generally have to use one of the built-in data structures to hold the data. Here’s one way to implement a stack using JavaScript, which uses an array under the hood:
| | class Stack { |
| | constructor() { |
| | this.data = []; |
| | } |
| | |
| | push(element) { |
| | this.data.push(element); |
| | } |
| | |
| | pop() { |
| | if (this.data.length > 0) { |
| | return this.data.pop(); |
| | } else { |
| | return null; |
| | } |
| | } |
| | |
| | read() { |
| | if (this.data.length > 0) { |
| | return this.data[this.data.length - 1]; ... |
Read now
Unlock full access