File tree 2 files changed +102
-0
lines changed
2 files changed +102
-0
lines changed Original file line number Diff line number Diff line change
1
+ #include < iostream>
2
+ #include < stack>
3
+ using namespace std ;
4
+
5
+ stack <int > st;
6
+
7
+ void enqueue () {
8
+ int val;
9
+ cin >> val;
10
+ st.push (val);
11
+ }
12
+
13
+ int dequeue () {
14
+ if (st.size () == 1 ) {
15
+ int val = st.top ();
16
+ st.pop ();
17
+ return val;
18
+ }
19
+ int curValue = st.top ();
20
+ st.pop ();
21
+ int rec = dequeue ();
22
+ st.push (curValue);
23
+ return rec;
24
+ }
25
+
26
+ int main () {
27
+ string cmd;
28
+ for (int i = 0 ; i < 10 ; i++) {
29
+ cin >> cmd;
30
+ if (tolower (cmd[0 ]) == ' e' ) { // cmd == "enqueue"
31
+ enqueue ();
32
+ }
33
+ else if (tolower (cmd[0 ]) == ' d' ) { // cmd == 'dequeue'
34
+ if (st.empty ()) {
35
+ printf (" Error: queue is empty\n " );
36
+ exit (EXIT_FAILURE);
37
+ }
38
+ int val = dequeue ();
39
+ printf (" dequeued: %d\n " , val);
40
+ }
41
+ }
42
+ return 0 ;
43
+ }
Original file line number Diff line number Diff line change
1
+ /*
2
+ it takes two stacks to perform the task,
3
+ but it's time efficient, only in Linear time
4
+
5
+ There are also another approach, which is
6
+ not time efficient, but use only one stack
7
+ */
8
+
9
+ #include < iostream>
10
+ #include < stack>
11
+ using namespace std ;
12
+
13
+ /*
14
+ | 3 | | 1 |
15
+ | 2 | | 2 |
16
+ | 1 | | 3 |
17
+ ----- -----
18
+ enq deq
19
+ */
20
+
21
+ stack<int > enq, deq;
22
+
23
+ void enqueue () {
24
+ int val;
25
+ cin >> val;
26
+ enq.push (val);
27
+ }
28
+
29
+ void dequeue () {
30
+ if (deq.empty ()) { // if deq empty, transfer all enq value to deq in reverse order
31
+ int val;
32
+ while (!enq.empty ()) {
33
+ int val = enq.top ();
34
+ enq.pop ();
35
+ deq.push (val);
36
+ }
37
+ }
38
+ if (deq.empty ()) { // if still empty
39
+ printf (" Error: queue is empty\n " );
40
+ exit (EXIT_FAILURE);
41
+ }
42
+ int val = deq.top ();
43
+ deq.pop ();
44
+ printf (" dequeued %d\n " , val);
45
+ }
46
+
47
+ int main () {
48
+ string cmd;
49
+ for (int i = 0 ; i < 10 ; i++) {
50
+ cin >> cmd;
51
+ if (tolower (cmd[0 ]) == ' e' ) { // cmd == "enqueue"
52
+ enqueue ();
53
+ }
54
+ else if (tolower (cmd[0 ]) == ' d' ) { // cmd == 'dequeue'
55
+ dequeue ();
56
+ }
57
+ }
58
+ return 0 ;
59
+ }
You can’t perform that action at this time.
0 commit comments