Skip to content

Instantly share code, notes, and snippets.

@bitcpf
Last active August 29, 2015 14:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bitcpf/317b70b2fc28c6134846 to your computer and use it in GitHub Desktop.
Save bitcpf/317b70b2fc28c6134846 to your computer and use it in GitHub Desktop.
import java.util.Stack;
import java.util.ArrayList;
public class SubStacks {
private ArrayList<substack> stacks;
private int sub_capacity;
private int cur_stack;
private class substack<T>{
Stack<T> stack;
int N;
public substack(){
this.stack = new Stack<T>();
this.N = 0;
}
public void push(T item){
stack.add(item);
N ++;
}
public T pop(){
if (N == 0) return null;
N --;
return stack.pop();
}
}
public SubStacks(int threshold){
stacks = new ArrayList<substack>();
stacks.add(new substack());
cur_stack = 0;
this.sub_capacity = threshold;
}
public <T> void push(T item){
substack temp = stacks.get(cur_stack);
if(temp.N >= sub_capacity){
substack new_temp = new substack();
stacks.add(new_temp);
temp = new_temp;
cur_stack ++;
}
temp.push(item);
}
public <T> T pop(){
while(stacks.get(cur_stack).N == 0 && cur_stack > 0) cur_stack --;
return (T) stacks.get(cur_stack).pop();
}
public <T> T popAt(int index){
if(index > cur_stack) return null;
return (T) stacks.get(index).pop();
}
public static void main(String[] args){
SubStacks test = new SubStacks(10);
for (int i = 0; i < 50; i++)
test.push(i);
System.out.println(test.popAt(2));
System.out.println(test.popAt(2));
System.out.println(test.popAt(2));
System.out.println(test.popAt(3));
for(int i = 0;i <10; i++){
System.out.println(test.pop());
}
System.out.println(test.pop());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment