-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathqueue.js
More file actions
76 lines (67 loc) 路 1.31 KB
/
Copy pathqueue.js
File metadata and controls
76 lines (67 loc) 路 1.31 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
//queue
class Node {
constructor(value) {
this.value = value;
this.next = null;
}
}
class Queue {
constructor() {
this.front = null;
this.rear = null;
this.size = 0;
}
isEmpty() {
return this.size === 0;
}
enqueue(value) {
const node = new Node(value);
if (this.isEmpty()) {
this.front = node;
this.rear = node;
this.size++;
return true;
}
this.rear.next = node;
this.rear = node;
this.size++;
return true;
}
dequeue() {
if (this.isEmpty()) {
return null;
}
const dequeuedItem = this.front;
if (this.front === this.rear) {
this.front = null;
this.rear = null;
} else {
this.front = this.front.next;
}
dequeuedItem.next = null;
this.size--;
return dequeuedItem.value;
}
}
//queue using stack
class QueueUsingStack {
constructor() {
this.enqueueStack = new Stack();
this.dequeueStack = new Stack();
}
enqueue(value) {
this.enqueueStack.push(value);
}
dequeue() {
if (this.dequeueStack.length === 0) {
if (this.enqueueStack.length === 0) {
return null;
} else {
while (this.enqueueStack.length > 0) {
this.dequeueStack.push(this.enqueueStack.pop());
}
}
return this.dequeueStack.pop();
}
}
}