-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathQueueUsingStacks.java
51 lines (41 loc) · 1.39 KB
/
QueueUsingStacks.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import java.util.Stack;
public class QueueUsingStacks {
private Stack<Integer> stack1;
private Stack<Integer> stack2;
public QueueUsingStacks() {//constructor which creates two empty stacks when called
stack1 = new Stack<>();
stack2 = new Stack<>();
}
public void push(int x) {//adds an element to the que
stack1.push(x);
}
public int pop() {//pehle sb ko transfer kia fir que k liye doosre stack k top ko pop 😉
if (stack2.isEmpty()) {
while (!stack1.isEmpty()) {
stack2.push(stack1.pop());
}
}
return stack2.pop();
}
public int peek() {//same thing as pop just no deletion only printing
if (stack2.isEmpty()) {
while (!stack1.isEmpty()) {
stack2.push(stack1.pop());
}
}
return stack2.peek();
}
public boolean empty() {//if both stacks empty => queue is empty
return stack1.isEmpty() && stack2.isEmpty();
}
public static void main(String[] args) {
QueueUsingStacks queue = new QueueUsingStacks();
queue.push(1);
queue.push(2);
queue.push(3);
System.out.println(queue.pop());
System.out.println(queue.pop());
System.out.println(queue.pop());
System.out.println(queue.empty());
}
}