-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathqueuebystack.java
More file actions
62 lines (50 loc) · 1005 Bytes
/
queuebystack.java
File metadata and controls
62 lines (50 loc) · 1005 Bytes
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
import java.util.Stack;
class Queue<T> {
private Stack<T> s;
// Constructor
Queue() {
s = new Stack<>();
}
// Add an item to the queue
public void enqueue(T data)
{
// push item into the first stack
s.push(data);
}
// Remove an item from the queue
public T dequeue()
{
// if the stack is empty
if (s.isEmpty())
{
System.out.println("Underflow!!");
System.exit(0);
}
// pop an item from the stack
T top = s.pop();
// if the stack becomes empty, return the popped item
if (s.isEmpty()) {
return top;
}
// recur
T item = dequeue();
// push popped item back into the stack
s.push(top);
// return the result of dequeue() call
return item;
}
}
class Main
{
public static void main(String[] args)
{
int[] keys = { 5, 4, 3, 2, 1 };
Queue<Integer> q = new Queue<Integer>();
// insert the above keys into the queue
for (int key: keys) {
q.enqueue(key);
}
System.out.println(q.dequeue());
System.out.println(q.dequeue());
}
}