File tree Expand file tree Collapse file tree 3 files changed +73
-6
lines changed
lib/data-structures/stacks Expand file tree Collapse file tree 3 files changed +73
-6
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * Data structure that adds and remove elements in a last-in, first-out (LIFO) fashion
3
+ */
4
+ class Stack {
5
+ constructor() {
6
+ this.input = [];
7
+ }
8
+
9
+ /**
10
+ * Add element into the stack
11
+ * Runtime: O(1)
12
+ * @param {any} element
13
+ */
14
+ add(element) {
15
+ this.input.push(element);
16
+ return this;
17
+ }
18
+
19
+ /**
20
+ * Remove element from the stack
21
+ * Runtime: O(1)
22
+ */
23
+ remove() {
24
+ return this.input.pop();
25
+ }
26
+
27
+ /**
28
+ * Size of the queue
29
+ */
30
+ get size() {
31
+ return this.input.length;
32
+ }
33
+ }
34
+
35
+ // aliases
36
+ Stack.prototype.push = Stack.prototype.add;
37
+ Stack.prototype.pop = Stack.prototype.remove;
38
+
39
+ module.exports = Stack;
40
+
Original file line number Diff line number Diff line change
1
+ const LinkedList = require('../linked-lists/linked-list');
2
+
3
+ /**
4
+ * Data structure that adds and remove elements in a last-in, first-out (LIFO) fashion
5
+ */
1
6
class Stack {
2
7
constructor() {
3
- this.input = [] ;
8
+ this.input = new LinkedList() ;
4
9
}
5
10
6
- push(element) {
7
- this.input.push(element);
11
+ /**
12
+ * Add element into the stack
13
+ * Runtime: O(1)
14
+ * @param {any} element
15
+ */
16
+ add(element) {
17
+ this.input.addLast(element);
8
18
return this;
9
19
}
10
20
11
- pop() {
12
- return this.input.pop();
21
+ /**
22
+ * Remove element from the stack
23
+ * Runtime: O(1)
24
+ */
25
+ remove() {
26
+ return this.input.removeLast();
27
+ }
28
+
29
+ /**
30
+ * Size of the queue
31
+ */
32
+ get size() {
33
+ return this.input.size;
13
34
}
14
35
}
15
36
37
+ // aliases
38
+ Stack.prototype.push = Stack.prototype.add;
39
+ Stack.prototype.pop = Stack.prototype.remove;
40
+
16
41
module.exports = Stack;
17
42
Original file line number Diff line number Diff line change @@ -9,8 +9,9 @@ describe('Stack', function () {
9
9
10
10
describe('#push', () => {
11
11
it('should push an element to the stack', () => {
12
+ expect(stack.size).toEqual(0);
12
13
stack.push(1);
13
- expect(stack.input ).toEqual([1] );
14
+ expect(stack.size ).toEqual(1 );
14
15
});
15
16
});
16
17
@@ -23,6 +24,7 @@ describe('Stack', function () {
23
24
it('should get last element entered', () => {
24
25
expect(stack.pop()).toEqual('b');
25
26
expect(stack.pop()).toEqual('a');
27
+ expect(stack.pop()).toEqual(undefined);
26
28
});
27
29
});
28
30
});
You can’t perform that action at this time.
0 commit comments