-
Notifications
You must be signed in to change notification settings - Fork 26
/
stack.js
59 lines (58 loc) · 1.36 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
58
59
class Node {
constructor(data) {
this.data = data;
this.next = null;
this.last = null;
}
}
export default class Stack {
constructor(data) {
this.head = null;
this.last = null;
this.size = 0;
}
push(data) {
const newNode = new Node(data);
if (this.head === null && this.size < 1) {
this.head = newNode;
} else {
let current = this.head;
while (current.next !== null) {
current = current.next;
}
current.next = newNode;
}
this.last = newNode;
this.size++;
}
pop() {
if (this.size === 0) {
return;
}
if (this.size === 1) {
const popElement = this.head;
this.head = null;
this.size--;
return popElement;
}
let current = this.head;
while (current.next.next !== null) {
current = current.next;
}
this.last = current;
let popElement = current.next;
current.next = null;
this.size--;
return popElement;
}
peek() {
return this.last;
}
print() {
let iterator = this.head;
while (iterator !== null) {
console.log(iterator.data);
iterator = iterator.next;
}
}
}