1
+ // --- Directions
2
+ // Implement a Queue datastructure using two stacks.
3
+ // *Do not* create an array inside of the 'Queue' class.
4
+ // Queue should implement the methods 'add', 'remove', and 'peek'.
5
+ // For a reminder on what each method does, look back
6
+ // at the Queue exercise.
7
+
8
+ // --- Examples
9
+ // const q = new Queue();
10
+ // q.add(1);
11
+ // q.add(2);
12
+ // q.peek(); should returns 1
13
+ // q.remove(); should returns 1
14
+ // q.remove(); should returns 2
15
+
16
+
17
+ // Solution
18
+
19
+ const Stack = require ( './stack' ) ;
20
+
21
+ class Queue {
22
+ constructor ( ) {
23
+ this . first = new Stack ( ) ;
24
+ this . second = new Stack ( ) ;
25
+ }
26
+
27
+ add ( record ) {
28
+ this . first . push ( record ) ;
29
+ }
30
+
31
+ remove ( ) {
32
+ while ( this . first . peek ( ) ) {
33
+ this . second . push ( this . first . pop ( ) ) ;
34
+ }
35
+
36
+ const record = this . second . pop ( ) ;
37
+
38
+ while ( this . second . peek ( ) ) {
39
+ this . first . push ( this . second . pop ( ) ) ;
40
+ }
41
+
42
+ return record ;
43
+ }
44
+
45
+
46
+ peek ( ) {
47
+ while ( this . first . peek ( ) ) {
48
+ this . second . push ( this . first . pop ( ) ) ;
49
+ }
50
+
51
+ const record = this . second . peek ( ) ;
52
+
53
+ while ( this . second . peek ( ) ) {
54
+ this . first . push ( this . second . pop ( ) ) ;
55
+ }
56
+ }
57
+ }
0 commit comments