-
-
Notifications
You must be signed in to change notification settings - Fork 317
/
Copy pathQueueViaStacks.java
61 lines (54 loc) · 1.58 KB
/
QueueViaStacks.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
package com.ctci.stacksandqueues;
import java.util.NoSuchElementException;
import java.util.Stack;
/**
* Implement a queue using two stacks. No other data structures to be used.
*
* @author rampatra
* @since 2019-02-06
*/
public class QueueViaStacks<T> {
private Stack<T> stackFront = new Stack<>();
private Stack<T> stackRear = new Stack<>();
private T add(T item) {
return stackRear.push(item);
}
private T remove() {
if (stackFront.empty() && stackRear.empty()) {
throw new NoSuchElementException();
} else if (!stackFront.empty()) {
return stackFront.pop();
} else {
while (!stackRear.empty()) {
stackFront.push(stackRear.pop());
}
return stackFront.pop();
}
}
private void print() {
Stack<T> tempStack = new Stack<>();
while (!stackFront.empty()) {
tempStack.push(stackFront.pop());
}
System.out.print("[");
tempStack.forEach(item -> System.out.print(item + ","));
stackRear.forEach(item -> System.out.print(item + ","));
System.out.println("]");
while (!tempStack.empty()) {
stackFront.push(tempStack.pop());
}
}
public static void main(String[] args) {
QueueViaStacks<Integer> queue = new QueueViaStacks<>();
queue.add(1);
queue.add(2);
queue.add(3);
queue.print();
queue.remove();
queue.print();
queue.remove();
queue.print();
queue.remove();
queue.print();
}
}