Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit 45eefc1

Browse files
committed
Queue via 2 stacks: done
1 parent 1e2a300 commit 45eefc1

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
package com.ctci.stacksandqueues;
2+
3+
import java.util.NoSuchElementException;
4+
import java.util.Stack;
5+
6+
/**
7+
* @author rampatra
8+
* @since 2019-02-06
9+
*/
10+
public class QueueViaStacks<T> {
11+
12+
private Stack<T> stackFront = new Stack<>();
13+
private Stack<T> stackRear = new Stack<>();
14+
15+
private T add(T item) {
16+
return stackRear.push(item);
17+
}
18+
19+
private T remove() {
20+
if (stackFront.empty() && stackRear.empty()) {
21+
throw new NoSuchElementException();
22+
} else if (!stackFront.empty()) {
23+
return stackFront.pop();
24+
} else {
25+
while (!stackRear.empty()) {
26+
stackFront.push(stackRear.pop());
27+
}
28+
return stackFront.pop();
29+
}
30+
}
31+
32+
private void print() {
33+
Stack<T> tempStack = new Stack<>();
34+
while (!stackFront.empty()) {
35+
tempStack.push(stackFront.pop());
36+
}
37+
System.out.print("[");
38+
tempStack.forEach(item -> System.out.print(item + ","));
39+
stackRear.forEach(item -> System.out.print(item + ","));
40+
System.out.println("]");
41+
while (!tempStack.empty()) {
42+
stackFront.push(tempStack.pop());
43+
}
44+
}
45+
46+
public static void main(String[] args) {
47+
QueueViaStacks<Integer> queue = new QueueViaStacks<>();
48+
queue.add(1);
49+
queue.add(2);
50+
queue.add(3);
51+
queue.print();
52+
queue.remove();
53+
queue.print();
54+
queue.remove();
55+
queue.print();
56+
queue.remove();
57+
queue.print();
58+
}
59+
}

0 commit comments

Comments
 (0)