1
+ /**
2
+ * Hackerrank
3
+ * A queue is an abstract data type that maintains the order in which elements
4
+ * were added to it, allowing the oldest elements to be removed from the front
5
+ * and new elements to be added to the rear. This is called a First-In-First-Out
6
+ * (FIFO) data structure because the first element added to the queue (i.e., the
7
+ * one that has been waiting the longest) is always the first one to be removed.
8
+ *
9
+ * In this challenge, you must first implement a queue using two stacks. Then
10
+ * process q queries, where each query is one of the following types:
11
+ *
12
+ * 1 x: Enqueue element x into the end of the queue.
13
+ * 2: Dequeue the element at the front of the queue.
14
+ * 3: Print the element at the front of the queue.
15
+ *
16
+ * Constraints:
17
+ * 1. 1 <= q <= 10^5
18
+ * 2. 1 <= type <= 3
19
+ * 3. 1 <= |x| <= 10^9
20
+ *
21
+ * This solution got 25 points
22
+ * Problem link: http://hr.gs/acbfeb
23
+ */
24
+ class Queue {
25
+ constructor ( ) {
26
+ this . principalStack = [ ] ;
27
+ this . auxStack = [ ] ;
28
+ }
29
+
30
+ /**
31
+ * Fill the auxiliar stack which is contains
32
+ * a reversed list of the main stack elements
33
+ */
34
+ fillAux ( ) {
35
+ if ( this . auxStack . length === 0 ) {
36
+ while ( this . principalStack . length > 0 ) {
37
+ this . auxStack . push ( this . principalStack . pop ( ) )
38
+ }
39
+ }
40
+ }
41
+
42
+ /**
43
+ * Insert a new element in the rear of the queue
44
+ */
45
+ enqueue ( value ) {
46
+ this . principalStack . push ( value ) ;
47
+ }
48
+
49
+ /**
50
+ * Remove the head element of the queue
51
+ */
52
+ dequeue ( ) {
53
+ this . fillAux ( ) ;
54
+ this . auxStack . pop ( ) ;
55
+ }
56
+
57
+ /**
58
+ * Print the rear element of the queue
59
+ */
60
+ printRear ( ) {
61
+ this . fillAux ( ) ;
62
+ const head = this . auxStack . pop ( ) ;
63
+ console . log ( head ) ;
64
+ this . auxStack . push ( head )
65
+ }
66
+ }
67
+ /**
68
+ *
69
+ * @param {string } input - Queries to bo processed
70
+ */
71
+ function processData ( input ) {
72
+ const ACTIONS = {
73
+ ENQEUE : '1' ,
74
+ DEQUEUE : '2' ,
75
+ PRINT : '3'
76
+ } ;
77
+ const queue = new Queue ( ) ;
78
+ input . split ( '\n' ) . forEach ( line => {
79
+ const query = line . split ( ' ' ) ;
80
+ switch ( query [ 0 ] ) {
81
+ case ACTIONS . ENQEUE :
82
+ queue . enqueue ( query [ 1 ] ) ;
83
+ break ;
84
+ case ACTIONS . DEQUEUE :
85
+ queue . dequeue ( ) ;
86
+ break ;
87
+ case ACTIONS . PRINT :
88
+ queue . printRear ( ) ;
89
+ break ;
90
+ }
91
+ } )
92
+ }
0 commit comments