forked from anthonynsimon/java-ds-algorithms
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathStackOfStacks.java
More file actions
83 lines (68 loc) · 2.07 KB
/
StackOfStacks.java
File metadata and controls
83 lines (68 loc) · 2.07 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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package com.anthonynsimon.algorithms.stacksqueues;
import com.anthonynsimon.datastructures.Stack;
// Holds multiple stacks in one stack
// Will push elements to a new stack if current stack
// is larger than the defined cap per stack
public class StackOfStacks<E> {
private int size;
private int cap;
private Stack<Stack<E>> master;
public StackOfStacks(int cap) {
if (cap <= 0) {
throw new IndexOutOfBoundsException("Must be of at least 1 slot cap per stack");
}
this.cap = cap;
this.master = new Stack<>();
}
// Adds a new item to the top stack
public void push(E item) {
// Ensure we have a stack with enough space before pushing item
ensureCapacity();
getCurrentStack().push(item);
this.size++;
}
// Pops and returns top item from top stack
public E pop() {
E temp = getCurrentStack().pop();
// Cleanup master stack if necessary
settle();
this.size--;
return temp;
}
// Returns top item of top stack
public E peek() {
return getCurrentStack().peek();
}
// Returns number of items held across all stacks
public int size() {
return this.size;
}
// Returns the number of stacks being managed
public int stackCount() {
return this.master.size();
}
private Stack<E> getCurrentStack() {
return this.master.peek();
}
// Check if we already filled the current stack,
// if so then create new stack and push it to master
private void ensureCapacity() {
if (master.size() == 0) {
addStackToMaster();
}
if (getCurrentStack().size() == cap) {
addStackToMaster();
}
}
// Check if we already emptied the current stack,
// if so then pop it from the master
private void settle() {
if (getCurrentStack().size() == 0) {
this.master.pop();
}
}
private void addStackToMaster() {
Stack<E> newStack = new Stack<>();
this.master.push(newStack);
}
}