Skip to content

Commit 9a93c3a

Browse files
added implemenation of stacks using queues
1 parent b1c23d7 commit 9a93c3a

File tree

2 files changed

+67
-0
lines changed

2 files changed

+67
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
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+
}

Trees/Questions/DiameterOfTree.cpp

Whitespace-only changes.

0 commit comments

Comments
 (0)