forked from anthonynsimon/java-ds-algorithms
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathQueueViaStacks.java
More file actions
62 lines (48 loc) · 1.45 KB
/
QueueViaStacks.java
File metadata and controls
62 lines (48 loc) · 1.45 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
62
package com.anthonynsimon.algorithms.stacksqueues;
import com.anthonynsimon.datastructures.Stack;
// Uses two stacks to implement a queue
public class QueueViaStacks<E> {
private Stack<E> newestStack;
private Stack<E> oldestStack;
public QueueViaStacks() {
this.newestStack = new Stack<>();
this.oldestStack = new Stack<>();
}
// Enqueues a new element by shifting all elements to
// a "newest at top" stack, and pushing to it the item
public void enqueue(E item) {
shiftToNewest();
this.newestStack.push(item);
}
// Dequeue by shifting all elements to
// an "oldest at top" stack, and popping the top item
public E dequeue() {
if (size() == 0) {
return null;
}
shiftToOldest();
return this.oldestStack.pop();
}
// Peeks by shifting all elements to
// an "oldest at top" stack, and peeking the top item
public E peek() {
if (size() == 0) {
return null;
}
shiftToOldest();
return this.oldestStack.peek();
}
public int size() {
return this.oldestStack.size() + this.newestStack.size();
}
private void shiftToNewest() {
while (oldestStack.size() != 0) {
newestStack.push(oldestStack.pop());
}
}
private void shiftToOldest() {
while (newestStack.size() != 0) {
oldestStack.push(newestStack.pop());
}
}
}