File tree 2 files changed +52
-2
lines changed
2 files changed +52
-2
lines changed Original file line number Diff line number Diff line change
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);
Original file line number Diff line number Diff line change @@ -15,8 +15,10 @@ class Stack {
15
15
peek ( ) {
16
16
return this . data [ this . data . length - 1 ] ;
17
17
}
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 ;
20
22
}
21
23
}
22
24
You can’t perform that action at this time.
0 commit comments