-
Notifications
You must be signed in to change notification settings - Fork 0
/
stack.js
45 lines (41 loc) · 764 Bytes
/
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
class Node {
constructor(value) {
this.value = value;
this.next = null;
}
}
class Stack {
constructor(value) {
const newNode = new Node(value);
this.top = newNode;
this.length = 1;
}
push(value) {
const newNode = new Node(value);
if (this.length === 0) {
this.top = newNode;
} else {
newNode.next = this.top;
this.top = newNode;
}
this.length += 1;
return this;
}
pop() {
if (this.length === 0) {
return null;
} else {
let temp = this.top;
this.top = temp.next;
temp.next = null;
this.length--;
return temp;
}
}
}
let myStack = new Stack(10);
myStack.push(12);
myStack.push(11);
myStack.push(13);
myStack.pop();
console.log(myStack);