forked from yangshun/lago
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathStack.js
57 lines (51 loc) · 1.08 KB
/
Stack.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import Node from './Node';
class Stack {
constructor() {
this._tail = null;
this.length = 0;
}
/**
* Adds an element to the top of the Stack.
* @param {*} element
* @return {number} The new length of the Stack.
*/
push(value) {
const node = new Node(value);
node.next = this._tail;
this._tail = node;
this.length++;
return this.length;
}
/**
* Removes the element at the top of the Stack.
* @return {number} The new length of the Stack.
*/
pop() {
if (this.isEmpty()) {
return undefined;
}
const node = this._tail;
this._tail = this._tail.next;
node.next = null;
this.length--;
return node.val;
}
/**
* Returns true if the Stack has no elements.
* @return {boolean} Whether the Stack has no elements.
*/
isEmpty() {
return this.length === 0;
}
/**
* Returns the element at the top of the Stack.
* @return {*} The element at the top of the Stack.
*/
peek() {
if (this.isEmpty()) {
return undefined;
}
return this._tail.val;
}
}
export default Stack;