-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQueueUsingStack.java
More file actions
61 lines (56 loc) · 1.22 KB
/
QueueUsingStack.java
File metadata and controls
61 lines (56 loc) · 1.22 KB
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
package datastructure.stackandqueue.queue;
import java.util.Stack;
/**
* The type Queue using stack.
*
* @param <V> the type parameter
*/
public class QueueUsingStack<V> {
/**
* The Stack 1.
*/
Stack<V> stack1 = new Stack<>();
/**
* The Stack 2.
*/
Stack<V> stack2 = new Stack<>();
/**
* Enqueue.
*
* @param value the value
*/
public void enqueue(V value){
stack1.push(value);
}
/**
* Dequeue v.
*
* @return the v
*/
public V dequeue(){
while(!stack1.empty()){
stack2.push(stack1.pop());
}
V result = stack2.pop();
while (!stack2.empty()){
stack1.push(stack2.pop());
}
return result;
}
/**
* Main.
*
* @param args the args
*/
public static void main(String[] args){
QueueUsingStack q = new QueueUsingStack();
q.enqueue(1);
q.enqueue(2);
q.enqueue(3);
q.enqueue(4);
System.out.println("Dequeue result is :: "+q.dequeue());
q.enqueue(5);
System.out.println("Dequeue result is :: "+q.dequeue());
System.out.println("Dequeue result is :: "+q.dequeue());
}
}