File tree 2 files changed +67
-0
lines changed
2 files changed +67
-0
lines changed Original file line number Diff line number Diff line change
1
+ #include < bits/stdc++.h>
2
+ using namespace std ;
3
+
4
+ int main () {
5
+ // usign two queues
6
+ // of course we can use here queue in class implementation
7
+ queue<int > q1;
8
+ queue<int > q2;
9
+ int i=0 ;
10
+ int num;
11
+ while (i<5 ){
12
+ cout<<" Enter a number to insert into stack" <<endl;
13
+ cin>>num;
14
+ // algo:
15
+ // 1. Push element to q2
16
+ // 2. add element by element to q2 until q1 is not empty
17
+ // 3. swap q1 and q2
18
+ q2.push (num);
19
+ while (!q1.empty ()){
20
+ q2.push (q1.front ());
21
+ q1.pop ();
22
+ }
23
+ swap (q1, q2);
24
+ i++;
25
+
26
+ }
27
+
28
+
29
+ while (!q1.empty ()){
30
+ cout<<q1.front ()<<" " ;
31
+ q1.pop ();
32
+ }
33
+
34
+ // TC: O(N)
35
+ // SC:O(2N)
36
+
37
+
38
+ // Optimization of above approach TCO(N) SC:O(2N)
39
+ // Just go on insert from bottom to the top in queue
40
+ queue<int > q3;
41
+ int j=0 ;
42
+ while (j<5 ){
43
+ cout<<" Enter the number that you want to insert into the stack:" <<endl;
44
+ int x;
45
+ cin>>x;
46
+ q3.push (x);
47
+ for (int i=0 ; i<q3.size ()-1 ; i++){
48
+ q3.push (q3.front ());
49
+ q3.pop ();
50
+ }
51
+
52
+ j++;
53
+
54
+ }
55
+
56
+
57
+ while (!q3.empty ()){
58
+ cout<<q3.front ()<<" " ;
59
+ q3.pop ();
60
+ }
61
+
62
+
63
+
64
+
65
+
66
+
67
+ }
You can’t perform that action at this time.
0 commit comments