-
Notifications
You must be signed in to change notification settings - Fork 153
/
queueFromStack.js
79 lines (63 loc) · 1.4 KB
/
queueFromStack.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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
/**
* Queue from stack
*/
// Class declaration for queue data structure
class Queue {
constructor(size) {
this.first = new Stack();
this.second = new Stack();
}
enqueue(element) {
this.first.push(element);
}
dequeue() {
// Empty first stack to second
while (this.first.peek()) {
this.second.push(this.first.pop());
}
const element = this.second.pop();
// Restore first stack
while (this.second.peek()) {
this.first.push(this.second.pop());
}
return element;
}
peek() {
while (this.first.peek()) {
this.second.push(this.first.pop());
}
const element = this.second.peek();
while (this.second.peek()) {
this.first.push(this.second.pop());
}
return element;
}
}
// Class declaration for stack data structure
class Stack {
constructor() {
this.data = [];
}
push(record) {
this.data.push(record);
}
pop() {
return this.data.pop();
}
peek() {
return this.data[this.data.length - 1];
}
}
const q = new Queue();
q.enqueue(1);
console.log(q.dequeue());
q.enqueue(1);
q.enqueue(2);
q.enqueue(3);
console.log(q.dequeue());
console.log(q.dequeue());
console.log(q.dequeue());
q.enqueue(1);
q.enqueue(2);
console.log(q.peek());
console.log(q.peek());