Skip to content

Commit 61049dc

Browse files
committed
update: reverse-first-k elements of a queue
1 parent d48713c commit 61049dc

File tree

2 files changed

+52
-2
lines changed

2 files changed

+52
-2
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
// eslint-disable-next-line no-unused-vars
2+
const Queue = require('../index');
3+
const Stack = require('../../Stack');
4+
5+
function reverseFirstKElelments(q, k) {
6+
const s = new Stack();
7+
8+
// push all the k elements ot the stack
9+
for (let i = 0; i < k; i += 1) {
10+
s.push(q.dequeue());
11+
}
12+
13+
// push the stack items to the queue
14+
for (let i = 0; i < k; i += 1) {
15+
q.enqueue(s.pop());
16+
}
17+
18+
// empty the queue and push the same queue
19+
const remaining = q.length() - k;
20+
for (let i = 0; i < remaining; i += 1) {
21+
q.enqueue(q.dequeue());
22+
}
23+
24+
// return the queue
25+
return q;
26+
}
27+
28+
module.exports = reverseFirstKElelments;
29+
30+
// let q = new Queue();
31+
32+
// q.enqueue(1);
33+
// q.enqueue(2);
34+
// q.enqueue(3);
35+
// q.enqueue(4);
36+
// q.enqueue(5);
37+
// q.enqueue(6);
38+
// q.enqueue(7);
39+
// q.enqueue(8);
40+
// q.enqueue(9);
41+
42+
// q = reverseFirstKElelments(q, 4);
43+
44+
// const arr = [];
45+
// while (q.length()) {
46+
// arr.push(q.dequeue());
47+
// }
48+
// console.log(arr);

src/_DataStructures_/Stack/index.js

+4-2
Original file line numberDiff line numberDiff line change
@@ -15,8 +15,10 @@ class Stack {
1515
peek() {
1616
return this.data[this.data.length - 1];
1717
}
18-
isEmpty(){ //check if stack is empty
19-
return this.data.length==0;
18+
19+
isEmpty() {
20+
// check if stack is empty
21+
return this.data.length === 0;
2022
}
2123
}
2224

0 commit comments

Comments
 (0)