-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQueue.js
More file actions
88 lines (79 loc) · 1.54 KB
/
Copy pathQueue.js
File metadata and controls
88 lines (79 loc) · 1.54 KB
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
// Implementing a queue
class Node {
constructor(value) {
this.value = value;
this.next = null;
}
}
class Queue {
constructor() {
this.first = null;
this.last = null;
this.length = 0;
}
peek() {
return this.first;
}
enqueue(value) {
const newNode = new Node(value);
if (this.isEmpty()) {
this.first = this.last = newNode;
return this;
}
const follower = this.last;
this.last = newNode;
this.last.next = follower;
this.length++;
return this;
}
dequeue() {
if (!this.first) {
return null;
}
if (this.first === this.last) {
this.last = null;
}
this.first = this.first.next;
this.length--;
return this;
}
isEmpty() {
if (this.first === null) return true;
return false;
}
}
const myQueue = new Queue();
myQueue.enqueue(1);
myQueue.enqueue(2);
myQueue.enqueue(3);
myQueue.enqueue(4);
myQueue.enqueue(5);
// Implementing a queue using a stack (array methods)
class CrazyQueue {
constructor() {
this.first = [];
this.last = [];
}
enqueue(value) {
const length = this.first.length;
for (let i = 0; i < length; i++) {
this.last.push(this.first.pop());
}
this.last.push(value);
return this;
}
dequeue() {
const length = this.last.length;
for (let i = 0; i < length; i++) {
this.first.push(this.last.pop());
}
this.first.pop();
return this;
}
peek() {
if (this.last.length > 0) {
return this.last[0];
}
return this.first[this.first.length - 1];
}
}