Created
June 23, 2014 09:35
-
-
Save chouclee/1e3eacb31d0bb2ea52c9 to your computer and use it in GitHub Desktop.
[CC150][3.3] Imagine a (literal) stack of plates If the stack gets too high, it might topple Therefore, in real life, we would likely start a new stack when the previous stack exceeds some threshold Implement a data structure SetOfStacks that mimics this SetOfStacks should be composed of several stacks, and should create a new stack once the pre…
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Stack; | |
import java.util.ArrayList; | |
public class SetOfStacks<T> { | |
private ArrayList<myStack> stacks; | |
private int threshold; | |
private int currIdx; | |
private class myStack { | |
Stack<T> stack; | |
int N; | |
public myStack() { | |
stack = new Stack<T>(); | |
N = 0; | |
} | |
public void push(T item) { | |
stack.add(item); | |
N++; | |
} | |
public T pop() { | |
if (N == 0) return null; | |
N--; | |
return stack.pop(); | |
} | |
} | |
public SetOfStacks (int threshold) { | |
stacks = new ArrayList<myStack>(); | |
stacks.add(new myStack()); | |
currIdx = 0; | |
this.threshold = threshold; | |
} | |
public void push(T item) { | |
myStack s = stacks.get(currIdx); | |
if (s.N >= threshold) { | |
currIdx++; | |
stacks.add(new myStack()); | |
stacks.get(currIdx).push(item); | |
} | |
else stacks.get(currIdx).push(item); | |
} | |
public T pop() { | |
while (stacks.get(currIdx).N == 0 && currIdx > 0) currIdx--; | |
return stacks.get(currIdx).pop(); | |
} | |
public T popAt(int index) { | |
if (index > currIdx) return null; | |
return stacks.get(index).pop(); | |
} | |
public String toString() { | |
StringBuilder sb = new StringBuilder(); | |
for (int i = 0; i <= currIdx; i++) { | |
for (T each : stacks.get(i).stack) { | |
sb.append(each.toString() + " "); | |
} | |
sb.append("\n"); | |
} | |
return sb.toString(); | |
} | |
public static void main(String[] args) { | |
SetOfStacks<Integer> test = new SetOfStacks<Integer>(10); | |
for (int i = 0; i < 60; i++) | |
test.push(i); | |
System.out.println(test.toString()); | |
for (int i = 0; i < 35; i++) | |
test.pop(); | |
System.out.println(test.toString()); | |
for (int i = 0; i < 35; i++) | |
test.push(i); | |
System.out.println(test.toString()); | |
for (int i = 0; i < 7; i++) | |
System.out.println(test.popAt(i)); | |
System.out.println(test.toString()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment