Skip to content

Commit 1925a2f

Browse files
committed
java: queue using stack
Signed-off-by: Ayush Dubey <[email protected]>
1 parent 27f02f6 commit 1925a2f

File tree

1 file changed

+75
-0
lines changed

1 file changed

+75
-0
lines changed

java/queueUsingStack.java

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
/* Java Program to implement a queue using two stacks */
2+
// Note that Stack class is used for Stack implementation
3+
4+
import java.util.Stack;
5+
6+
public class queueUsingStack {
7+
/* class of queue having two stacks */
8+
static class Queue {
9+
Stack<Integer> stack1;
10+
Stack<Integer> stack2;
11+
}
12+
13+
/* Function to push an item to stack */
14+
static void push(Stack<Integer> top_ref, int new_data) {
15+
// Push the data onto the stack
16+
top_ref.push(new_data);
17+
}
18+
19+
/* Function to pop an item from stack */
20+
static int pop(Stack<Integer> top_ref) {
21+
/* If stack is empty then error */
22+
if (top_ref.isEmpty()) {
23+
System.out.println("Stack Underflow");
24+
System.exit(0);
25+
}
26+
27+
// pop the data from the stack
28+
return top_ref.pop();
29+
}
30+
31+
// Function to enqueue an item to the queue
32+
static void enQueue(Queue q, int x) {
33+
push(q.stack1, x);
34+
}
35+
36+
/* Function to deQueue an item from queue */
37+
static int deQueue(Queue q) {
38+
int x;
39+
40+
/* If both stacks are empty then error */
41+
if (q.stack1.isEmpty() && q.stack2.isEmpty()) {
42+
System.out.println("Q is empty");
43+
System.exit(0);
44+
}
45+
46+
/*
47+
* Move elements from stack1 to stack 2 only if
48+
* stack2 is empty
49+
*/
50+
if (q.stack2.isEmpty()) {
51+
while (!q.stack1.isEmpty()) {
52+
x = pop(q.stack1);
53+
push(q.stack2, x);
54+
}
55+
}
56+
x = pop(q.stack2);
57+
return x;
58+
}
59+
60+
/* Driver function to test above functions */
61+
public static void main(String args[]) {
62+
/* Create a queue with items 1 2 3 */
63+
Queue q = new Queue();
64+
q.stack1 = new Stack<>();
65+
q.stack2 = new Stack<>();
66+
enQueue(q, 1);
67+
enQueue(q, 2);
68+
enQueue(q, 3);
69+
70+
/* Dequeue items */
71+
System.out.print(deQueue(q) + " ");
72+
System.out.print(deQueue(q) + " ");
73+
System.out.println(deQueue(q) + " ");
74+
}
75+
}

0 commit comments

Comments
 (0)