forked from the-moonLight0/Hactober-fest-2021
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ImplementationOfQueueUsingTwoStacks.java
67 lines (56 loc) · 1.37 KB
/
ImplementationOfQueueUsingTwoStacks.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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
//Implementing Queue using two Stacks
import java.util.Stack;
public class queue_using_2stacks {
public static void main(String[] args) {
QueueStacks obj =new QueueStacks();
obj.enQueue(1);
obj.enQueue(2);
obj.enQueue(3);
System.out.println(obj.dequeue());
obj.enQueue(4);
obj.enQueue(5);
obj.enQueue(6);
System.out.println(obj.peek());
System.out.println(obj.peek());
System.out.println(obj.dequeue());
System.out.println(obj.dequeue());
System.out.println(obj.dequeue());
System.out.println(obj.dequeue());
}
}
class QueueStacks{
Stack <Integer> s1;
Stack <Integer> s2;
int size;
public QueueStacks(){
s1=new Stack<>();
s2=new Stack<>();
}
public int size(){
size=s1.size()+s2.size();
return size;
}
public void enQueue(int value){
s1.push(value);
}
public void exchangeStacks(){
int element=s1.pop();
s2.push(element);
}
public int dequeue(){
if(s2.isEmpty()){
while(!s1.isEmpty()){
exchangeStacks();
}
}
return s2.pop();
}
public int peek(){
if(s2.isEmpty()){
while(!s1.isEmpty()){
exchangeStacks();
}
}
return s2.peek();
}
}