Skip to content

Commit 443864e

Browse files
committed
added algo for stack using 2 queues in cpp
1 parent 96c0dca commit 443864e

File tree

1 file changed

+94
-0
lines changed

1 file changed

+94
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,94 @@
1+
#include<iostream>
2+
using namespace std;
3+
4+
struct qu1// queue1 declaration {
5+
qu1 *n1;
6+
int d1;
7+
}*f1 = NULL, *r1 = NULL, *q1 = NULL, *p1 = NULL, *np1 = NULL;
8+
9+
struct qu2// queue2 declaration {
10+
qu2 *n2;
11+
int d2;
12+
}*f2 = NULL, *r2 = NULL, *q2 = NULL, *p2 = NULL, *np2 = NULL;
13+
14+
void enqueue1(int a) {
15+
np1 = new qu1;
16+
np1->d1 = a;
17+
np1->n1 = NULL;
18+
if (f1 == NULL) {
19+
r1 = np1;
20+
r1->n1 = NULL;
21+
f1 = r1;
22+
} else {
23+
r1->n1 = np1;
24+
r1 = np1;
25+
r1->n1 = NULL;
26+
}
27+
}
28+
29+
int dequeue1() {
30+
int a;
31+
if (f1 == NULL) {
32+
cout<<"no elements present in queue\n";
33+
} else {
34+
q1 = f1;
35+
f1 = f1->n1;
36+
a = q1->d1;
37+
delete(q1);
38+
return a;
39+
}
40+
}
41+
42+
void enqueue2(int a) {
43+
np2 = new qu2;
44+
np2->d2 = a;
45+
np2->n2 = NULL;
46+
if (f2 == NULL) {
47+
r2 = np2;
48+
r2->n2 = NULL;
49+
f2 = r2;
50+
} else {
51+
r2->n2 = np2;
52+
r2 = np2;
53+
r2->n2 = NULL;
54+
}
55+
}
56+
57+
int dequeue2() {
58+
int a;
59+
if (f2 == NULL) {
60+
cout<<"no elements present in queue\n";
61+
} else {
62+
q2 = f2;
63+
f2 = f2->n2;
64+
a = q2->d2;
65+
delete(q2);
66+
return a;
67+
}
68+
}
69+
70+
int main() {
71+
int n, a, i = 0;
72+
cout<<"Enter the number of elements to be entered into stack\n";
73+
cin>>n;
74+
while (i < n) {
75+
cout<<"enter the element to be entered\n";
76+
cin>>a;
77+
enqueue1(a);
78+
i++;
79+
}
80+
cout<<"\n\nElements popped\n\n";
81+
while (f1 != NULL || f2 != NULL)// if both queues are not null {
82+
if (f2 == NULL)// if queue 2 is null {
83+
while (f1->n1 != NULL) {
84+
enqueue2(dequeue1());
85+
}
86+
cout<<dequeue1()<<endl;
87+
} else if (f1 == NULL)//if queue 1 is null {
88+
while (f2->n2 != NULL) {
89+
enqueue1(dequeue2());
90+
}
91+
cout<<dequeue2()<<endl;
92+
}
93+
}
94+
}

0 commit comments

Comments
 (0)