IN C++
- [(1)] Design a Stack that is composed ONLY of one or two Queue objects ergo the ONLY instance variables that exist in this stack are queues. Stack class should contain the following methods: Print, Pop, Push, Top, Size, isEmpty, copy [(2)] Design a Queue that is composed ONLY of two Stacks objects ergo the ONLY instance variables that exist in this queue are stacks. Queue class should contain the following methods: Print, Enqueue, Dequeue, Front, Rear, Size, isEmpty, Copy
ANSWER :-
1) Program to implement a stack
using two queue -
#include <iostream>
using
namespace
std;
class
Stack {
queue<
int
>
q1, q2;
int
curr_size;
public:
Stack()
{
curr_size
= 0;
}
void
push(
int
x)
{
curr_size++;
// Push x first in empty q2
q2.push(x);
// Push all the remaining
//
elements in q1 to q2.
while
(!q1.empty()) {
q2.push(q1.front());
q1.pop();
}
queue<
int
>
q = q1;
q1
= q2;
q2
= q;
}
void
pop()
{
// if no elements are there in q1
if
(q1.empty())
return
;
q1.pop();
curr_size--;
}
int
top()
{
if
(q1.empty())
return
-1;
return
q1.front();
}
int
size()
{
return
curr_size;
}
};
// Driver code
int
main()
{
Stack s;
s.push(1);
s.push(2);
s.push(3);
cout <<
"current size: "
<< s.size()
<<
endl;
cout << s.top()
<< endl;
s.pop();
cout << s.top()
<< endl;
s.pop();
cout << s.top()
<< endl;
cout <<
"current size: "
<< s.size()
<<
endl;
return
0;
}
2) program implement queue using two stack-
#include <iostream>
using
namespace
std;
class Queue {
public:
Stack S1, S2;
//declaring enqueue method
void enqueue(int x);
//declaring dequeue method
int dequeue();
};
// enqueue function
void Queue :: enqueue(int x)
{
S1.push(x);
cout << "Element Inserted into Queue\n";
}
// dequeue function
int Queue :: dequeue()
{
int x, y;
while(!S1.isEmpty())
{
// take an element out of first stack
x = S1.pop();
// insert it into the second stack
S2.push(x);
}
y = S2.pop();
while(!S2.isEmpty())
{
x = S2.pop();
S1.push(x);
}
return y;
}
// main function
int main()
{
Queue q;
q.enqueue(10);
q.enqueue(100);
q.enqueue(1000);
cout << "Removing element from queue" <<
q.dequeue();
return 0;
}
Get Answers For Free
Most questions answered within 1 hours.