|
1 | 1 | package stacks_queues;
|
2 | 2 |
|
| 3 | +import java.util.Stack; |
| 4 | + |
3 | 5 | public class QueueUsingStacks {
|
| 6 | + |
| 7 | + Stack<Integer> stack1 = new Stack<Integer>(); |
| 8 | + Stack<Integer> stack2 = new Stack<Integer>(); |
| 9 | + |
| 10 | + void enqueue(int data) { |
| 11 | + stack1.push(data); |
| 12 | + } |
| 13 | + |
| 14 | + boolean isEmpty() { |
| 15 | + return stack1.size() + stack2.size() == 0; |
| 16 | + } |
| 17 | + |
| 18 | + int dequeue() throws Exception { |
| 19 | + if(isEmpty()) { |
| 20 | + throw new Exception("queue is empty"); |
| 21 | + } |
| 22 | + |
| 23 | + if(stack2.isEmpty()) { |
| 24 | + while(!stack1.isEmpty()){ |
| 25 | + stack2.push(stack1.pop()); |
| 26 | + } |
| 27 | + } |
| 28 | + |
| 29 | + return stack2.pop(); |
| 30 | + } |
| 31 | + |
| 32 | + |
| 33 | + public static void main(String[] args) throws Exception { |
| 34 | + |
| 35 | + QueueUsingStacks q1 = new QueueUsingStacks(); |
| 36 | + |
| 37 | + q1.enqueue(1); |
| 38 | + q1.enqueue(2); |
| 39 | + q1.enqueue(3); |
| 40 | + |
| 41 | + System.out.println(q1.dequeue()); |
| 42 | + System.out.println(q1.dequeue()); |
| 43 | + |
| 44 | + q1.enqueue(4); |
| 45 | + q1.enqueue(5); |
| 46 | + q1.enqueue(6); |
| 47 | + |
| 48 | + System.out.println(q1.dequeue()); |
| 49 | + System.out.println(q1.dequeue()); |
4 | 50 |
|
5 | | - public static void main(String[] args) { |
6 | | - // TODO Auto-generated method stub |
7 | 51 |
|
8 | 52 | }
|
9 | 53 |
|
|
0 commit comments