|
| 1 | +// stack using queue |
| 2 | +#include <iostream> |
| 3 | +#include <queue> |
| 4 | + |
| 5 | +class StackUsingQueues { |
| 6 | +public: |
| 7 | + StackUsingQueues() {} |
| 8 | + |
| 9 | + // Push an element onto the stack. |
| 10 | + void push(int x) { |
| 11 | + // Add the element to the primary queue. |
| 12 | + primaryQueue.push(x); |
| 13 | + } |
| 14 | + |
| 15 | + // Remove and return the top element of the stack. |
| 16 | + int pop() { |
| 17 | + if (isEmpty()) { |
| 18 | + throw std::runtime_error("Stack is empty"); |
| 19 | + } |
| 20 | + |
| 21 | + // Move elements from the primary queue to the temporary queue except the last one. |
| 22 | + while (primaryQueue.size() > 1) { |
| 23 | + tempQueue.push(primaryQueue.front()); |
| 24 | + primaryQueue.pop(); |
| 25 | + } |
| 26 | + |
| 27 | + // Get the last element from the primary queue (top of the stack). |
| 28 | + int topElement = primaryQueue.front(); |
| 29 | + primaryQueue.pop(); |
| 30 | + |
| 31 | + // Swap the primary and temporary queues. |
| 32 | + primaryQueue = tempQueue; |
| 33 | + while (!tempQueue.empty()) { |
| 34 | + tempQueue.pop(); |
| 35 | + } |
| 36 | + |
| 37 | + return topElement; |
| 38 | + } |
| 39 | + |
| 40 | + // Return the top element of the stack without removing it. |
| 41 | + int top() { |
| 42 | + if (isEmpty()) { |
| 43 | + throw std::runtime_error("Stack is empty"); |
| 44 | + } |
| 45 | + |
| 46 | + int topElement = pop(); |
| 47 | + |
| 48 | + // Add the top element back to the stack. |
| 49 | + push(topElement); |
| 50 | + |
| 51 | + return topElement; |
| 52 | + } |
| 53 | + |
| 54 | + // Check if the stack is empty. |
| 55 | + bool isEmpty() { |
| 56 | + return primaryQueue.empty(); |
| 57 | + } |
| 58 | + |
| 59 | +private: |
| 60 | + std::queue<int> primaryQueue; |
| 61 | + std::queue<int> tempQueue; |
| 62 | +}; |
| 63 | + |
| 64 | +int main() { |
| 65 | + StackUsingQueues stack; |
| 66 | + |
| 67 | + // Push elements onto the stack. |
| 68 | + stack.push(1); |
| 69 | + stack.push(2); |
| 70 | + stack.push(3); |
| 71 | + |
| 72 | + // Pop elements from the stack. |
| 73 | + std::cout << stack.pop() << std::endl; // Output: 3 |
| 74 | + std::cout << stack.pop() << std::endl; // Output: 2 |
| 75 | + |
| 76 | + // Push more elements. |
| 77 | + stack.push(4); |
| 78 | + stack.push(5); |
| 79 | + |
| 80 | + // Peek at the top element. |
| 81 | + std::cout << stack.top() << std::endl; // Output: 5 |
| 82 | + |
| 83 | + // Check if the stack is empty. |
| 84 | + std::cout << stack.isEmpty() << std::endl; // Output: 0 (false) |
| 85 | + |
| 86 | + return 0; |
| 87 | +} |
0 commit comments