File tree Expand file tree Collapse file tree 2 files changed +80
-0
lines changed Expand file tree Collapse file tree 2 files changed +80
-0
lines changed Original file line number Diff line number Diff line change
1
+ /* Program to implement a stack using
2
+ two queue */
3
+ #include < bits/stdc++.h>
4
+ using namespace std ;
5
+
6
+ class Stack
7
+ {
8
+ queue<int > q1, q2;
9
+
10
+ int curr_size;
11
+
12
+ public:
13
+ Stack ()
14
+ {
15
+ curr_size = 0 ;
16
+ }
17
+
18
+ void push (int x)
19
+ {
20
+ curr_size++;
21
+
22
+ // Push x first in empty q2
23
+ q2.push (x);
24
+
25
+ // Push all the remaining
26
+ // elements in q1 to q2.
27
+ while (!q1.empty ())
28
+ {
29
+ q2.push (q1.front ());
30
+ q1.pop ();
31
+ }
32
+
33
+ // swap the names of two queues
34
+ queue<int > q = q1;
35
+ q1 = q2;
36
+ q2 = q;
37
+ }
38
+
39
+ void pop (){
40
+
41
+ // if no elements are there in q1
42
+ if (q1.empty ())
43
+ return ;
44
+ q1.pop ();
45
+ curr_size--;
46
+ }
47
+
48
+ int top ()
49
+ {
50
+ if (q1.empty ())
51
+ return -1 ;
52
+ return q1.front ();
53
+ }
54
+
55
+ int size ()
56
+ {
57
+ return curr_size;
58
+ }
59
+ };
60
+
61
+ // main function
62
+ int main ()
63
+ {
64
+ Stack stk;
65
+ stk.push (1 );
66
+ stk.push (2 );
67
+ stk.push (3 );
68
+
69
+ cout << " current size: " << stk.size ()
70
+ << endl;
71
+ cout << stk.top () << endl;
72
+ stk.pop ();
73
+ cout << stk.top () << endl;
74
+ stk.pop ();
75
+ cout << stk.top () << endl;
76
+
77
+ cout << " current size: " << stk.size ()
78
+ << endl;
79
+ return 0 ;
80
+ }
You can’t perform that action at this time.
0 commit comments