forked from Midway91/HactoberFest2023
-
Notifications
You must be signed in to change notification settings - Fork 0
/
QueueUsing2stacks.java
50 lines (43 loc) · 948 Bytes
/
QueueUsing2stacks.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
//Implementation of Queue Using two stacks
import java.util.*;
class QueueUsing2stacks{
Stack<Object> s1= new Stack<>();
Stack<Object> s2= new Stack<>();
public boolean IsEmpty() {
return s1.isEmpty();
}
public void enqueue(Object data) {
while(!s1.isEmpty()){
s2.push(s1.pop());
}
s1.push(data);
while(!s2.isEmpty()){
s1.push(s2.pop());
}
}
public Object dequeue() {
if(s1.isEmpty()){
System.out.println("Empty queue");
return -1;
}
return s1.pop();
}
public Object peek() {
if(s1.isEmpty()){
System.out.println("Empty queue");
return -1;
}
return s1.peek();
}
public static void main(String[] args) {
QueueUsing2stacks q1=new QueueUsing2stacks();
q1.enqueue("w");
q1.enqueue("4");
q1.enqueue("j");
q1.enqueue("1");
while(!q1.IsEmpty()){
System.out.println( q1.peek());
q1.dequeue();
}
}
}