Skip to content

Commit 62c97f2

Browse files
committed
queue from 2 stack
1 parent ff4f3c6 commit 62c97f2

3 files changed

Lines changed: 57 additions & 109 deletions

File tree

queue/Question/JosephusProblem.java

Lines changed: 0 additions & 57 deletions
This file was deleted.

queue/Question/SlidingWindowMax.java

Lines changed: 0 additions & 52 deletions
This file was deleted.

queue/basic/QueueFromStack.java

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
// you are given two stacks and using that make a queue
2+
3+
package queue.basic;
4+
5+
import java.util.Stack;
6+
7+
public class QueueFromStack {
8+
static Stack<Integer> stack1 = new Stack<>();
9+
static Stack<Integer> stack2 = new Stack<>();
10+
11+
public boolean isEmpty() {
12+
return stack1.isEmpty();
13+
}
14+
15+
public void enqueue(int element) {
16+
while (!stack1.isEmpty()) {
17+
stack2.push(stack1.pop());
18+
}
19+
20+
stack1.push(element);
21+
22+
while (!stack2.isEmpty()) {
23+
stack1.push(stack2.pop());
24+
}
25+
}
26+
27+
public int dequeue() {
28+
if (stack1.isEmpty()) {
29+
System.out.println("Queue is empty");
30+
return -1;
31+
}
32+
33+
return stack1.pop();
34+
}
35+
36+
public int poll() {
37+
if (stack1.isEmpty()) {
38+
System.out.println("Empty queue");
39+
return -1;
40+
}
41+
return stack1.peek();
42+
}
43+
44+
public static void main(String[] args) {
45+
QueueFromStack queue = new QueueFromStack();
46+
47+
queue.enqueue(1);
48+
queue.enqueue(2);
49+
queue.enqueue(3);
50+
queue.enqueue(4);
51+
52+
while (!queue.isEmpty()) {
53+
System.out.print(queue.poll() + " ");
54+
queue.dequeue();
55+
}
56+
}
57+
}

0 commit comments

Comments
 (0)