* fix: restructure certifications guide articles * fix: added 3 dashes line before prob expl * fix: added 3 dashes line before hints * fix: added 3 dashes line before solutions
84 lines
1.8 KiB
Markdown
84 lines
1.8 KiB
Markdown
---
|
|
title: Create a Stack Class
|
|
---
|
|
# Create a Stack Class
|
|
|
|
---
|
|
## Problem Explanation
|
|
- Stack is an abstract data structure.
|
|
- Stack follows LIFO/FILO principle.
|
|
- In this challenge, we need to add `.push()`, `.pop()`, `.peek()`, `.isEmpty()` and `.clear()` methods to the class.
|
|
-
|
|
- `push()` method pushes value to the stack.
|
|
- `pop()` method pops the first value from the stack.
|
|
- `peek()` method returns the first value from the stack.
|
|
- `isEmpty()` method checks if ths stack is empty.
|
|
- `.clear()` method removes all the elements from the stack.
|
|
-
|
|
| DS | Access | Search | Insert | Delete |
|
|
| ----- | ------ | ------ | ------ | ------ |
|
|
| Stack | n | n | 1 | 1 |
|
|
|
|
|
|
---
|
|
## Solutions
|
|
|
|
<details><summary>Solution 1 (Click to Show/Hide)</summary>
|
|
|
|
```js
|
|
function Stack() {
|
|
var collection = [];
|
|
this.print = function() {
|
|
console.log(collection);
|
|
};
|
|
this.push = function(val) {
|
|
return collection.push(val);
|
|
};
|
|
this.pop = function() {
|
|
return collection.pop();
|
|
};
|
|
this.peek = function() {
|
|
return collection[collection.length - 1];
|
|
};
|
|
this.isEmpty = function() {
|
|
return collection.length === 0;
|
|
};
|
|
this.clear = function() {
|
|
collection.length = 0;
|
|
};
|
|
}
|
|
```
|
|
</details>
|
|
|
|
<details><summary>Solution 2 (Click to Show/Hide)</summary>
|
|
|
|
```js
|
|
class Stack {
|
|
constructor() {
|
|
this.collection = [];
|
|
}
|
|
print() {
|
|
console.log(this.collection);
|
|
}
|
|
push(val) {
|
|
return this.collection.push(val);
|
|
}
|
|
pop() {
|
|
return this.collection.pop();
|
|
}
|
|
peek() {
|
|
return this.collection[this.collection.length - 1];
|
|
}
|
|
isEmpty() {
|
|
return this.collection.length === 0;
|
|
}
|
|
clear() {
|
|
return (this.collection.length = 0);
|
|
}
|
|
}
|
|
```
|
|
#### Relevant Links
|
|
|
|
- [Wikipedia](https://en.wikipedia.org/wiki/Stack_(abstract_data_type))
|
|
</details>
|