Program to Implement Stack using two Queues in Data Structures (C plus plus)
Program to Implement Stack using two Queues in Data Structures (C plus plus)
In this tutorial, we will learn about the Program to Implement Stack using two Queues in Data Structures (C plus plus).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 |
/*C++ Program to Implement Stack using Two Queues*/ #include<iostream> using namespace std; struct queue1 { queue1 *next1; int d1; } *front1 = NULL, *rear1 = NULL, *q1 = NULL, *p1 = NULL, *np1 = NULL; struct queue2 { queue2 *next2; int d2; } *front2 = NULL, *rear2 = NULL, *q2 = NULL, *p2 = NULL, *np2 = NULL; void enqueue_1(int x) { np1 = new queue1; np1->d1 = x; np1->next1 = NULL; if (front1 == NULL) { rear1 = np1; rear1->next1 = NULL; front1 = rear1; } else { rear1->next1 = np1; rear1 = np1; rear1->next1 = NULL; } } int dequeue_1() { int x; if (front1 == NULL) { cout<<"Queue is Empty "<<endl; } else { q1 = front1; front1 = front1->next1; x = q1->d1; delete(q1); return x; } } void enqueue_2(int x) { np2 = new queue2; np2->d2 = x; np2->next2 = NULL; if (front2
== NULL) { rear2 = np2; rear2->next2 = NULL; front2=rear2; } else { rear2->next2 = np2; rear2 = np2; rear2->next2 = NULL; } } int dequeue_2() { int x; if (front2 == NULL) { cout<<"Queue is empty "<<endl; } else { q2 = front2; front2 = front2->next2; x = q2->d2; delete(q2); return x; } } int main() { int num, val, s = 0; cout<<"Please enter the no of elements to be entered into stack: "<<endl; cin>>num; while (s < num) { cout<<"Please enter the desired values to be entered: "<<endl; cin>>val; enqueue_1(val); s++; } cout<<endl<<"Elements deleted "<<endl; while (front1 != NULL || front2 != NULL) { if (front2 == NULL) { while (front1->next1 != NULL) { enqueue_2(dequeue_1()); } cout<<dequeue_1()<<endl; } else if (front1 == NULL) { while (front2->next2 != NULL) { enqueue_1(dequeue_2()); } cout<<dequeue_2()<<endl; } } } |
Output: