|
| 1 | +// stack using queue |
| 2 | +import java.util.LinkedList; |
| 3 | +import java.util.Queue; |
| 4 | + |
| 5 | +public class StackUsingQueues { |
| 6 | + private Queue<Integer> primaryQueue; |
| 7 | + private Queue<Integer> tempQueue; |
| 8 | + |
| 9 | + public StackUsingQueues() { |
| 10 | + primaryQueue = new LinkedList<>(); |
| 11 | + tempQueue = new LinkedList<>(); |
| 12 | + } |
| 13 | + |
| 14 | + public void push(int value) { |
| 15 | + // Add the element to the primary queue |
| 16 | + primaryQueue.offer(value); |
| 17 | + } |
| 18 | + |
| 19 | + public int pop() { |
| 20 | + if (isEmpty()) { |
| 21 | + throw new IllegalStateException("Stack is empty."); |
| 22 | + } |
| 23 | + |
| 24 | + // Move elements from the primary queue to the temporary queue except the last one |
| 25 | + while (primaryQueue.size() > 1) { |
| 26 | + tempQueue.offer(primaryQueue.poll()); |
| 27 | + } |
| 28 | + |
| 29 | + // Get the last element from the primary queue (top of the stack) |
| 30 | + int topElement = primaryQueue.poll(); |
| 31 | + |
| 32 | + // Swap the primary and temporary queues |
| 33 | + Queue<Integer> swap = primaryQueue; |
| 34 | + primaryQueue = tempQueue; |
| 35 | + tempQueue = swap; |
| 36 | + |
| 37 | + return topElement; |
| 38 | + } |
| 39 | + |
| 40 | + public int top() { |
| 41 | + if (isEmpty()) { |
| 42 | + throw new IllegalStateException("Stack is empty."); |
| 43 | + } |
| 44 | + |
| 45 | + int topElement = pop(); |
| 46 | + |
| 47 | + // Add the top element back to the stack |
| 48 | + push(topElement); |
| 49 | + |
| 50 | + return topElement; |
| 51 | + } |
| 52 | + |
| 53 | + public boolean isEmpty() { |
| 54 | + return primaryQueue.isEmpty(); |
| 55 | + } |
| 56 | + |
| 57 | + public static void main(String[] args) { |
| 58 | + StackUsingQueues stack = new StackUsingQueues(); |
| 59 | + |
| 60 | + // Push elements onto the stack |
| 61 | + stack.push(1); |
| 62 | + stack.push(2); |
| 63 | + stack.push(3); |
| 64 | + |
| 65 | + // Pop elements from the stack |
| 66 | + System.out.println(stack.pop()); // Output: 3 |
| 67 | + System.out.println(stack.pop()); // Output: 2 |
| 68 | + |
| 69 | + // Push more elements |
| 70 | + stack.push(4); |
| 71 | + stack.push(5); |
| 72 | + |
| 73 | + // Peek at the top element |
| 74 | + System.out.println(stack.top()); // Output: 5 |
| 75 | + |
| 76 | + // Check if the stack is empty |
| 77 | + System.out.println(stack.isEmpty()); // Output: false |
| 78 | + } |
| 79 | +} |
0 commit comments