InterviewSolution
Saved Bookmarks
| 1. |
What is RTTI and how it can be implemented? |
|
Answer» Below is the logic for the implementation of the above logic In the en-QUEUE operation, the new element is entered at the top of Stack1. In de-queue operation, if Stack2 is empty then all the elements are moved to Stack2 and top of Stack2 is returned. enQueue(q, k): Push the element ‘k’ to Stack1 deQueue(q): While Stack1 is not empty and Stack2 is empty, pop the elements from Stack1 and push to Stack2. The top of the Stack2 popped out is returned. Program to perform the above: #include <iostream> using namespace STD; // implementing the stack class class Stack { int top; public: int a[10]; //Maximum size of Stack Stack() { top = -1; } // declaring all the function void push(int x); int pop(); bool ISEMPTY(); }; // function to insert data into stack void Stack::push(int x) { if(top >= 10) { cout << "Stack OVERFLOW"; } else { a[++top] = x; cout << endl<< "Element Inserted into Stack"<< x ; } } // function to remove data from the top of the stack int Stack::pop() { if(top < 0) { cout << "Stack Underflow \n"; return 0; } else { return (a[top--]); } } // function to check if stack is empty bool Stack::isEmpty() { if(top < 0) { return true; } else { return false; } } // implementing the queue class 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 "<< x << endl; } // 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); } // removing the element y = S2.pop(); // moving back the elements to the first stack 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 << endl<< "Removing element from queue" << q.dequeue(); return 0; }Output: Element Inserted into Stack10Element Inserted into Queue 10 Element Inserted into Stack100Element Inserted into Queue 100 Element Inserted into Stack1000Element Inserted into Queue 1000 Element Inserted into Stack1000 Element Inserted into Stack100 Element Inserted into Stack10 Element Inserted into Stack100 Element Inserted into Stack1000 Removing element from queue10 |
|