import java.util.ArrayList;
public class SetOfStacksApp {
public static void main(String[] args) {
int capacity_per_substack = 5;
SetOfStacks set = new SetOfStacks(capacity_per_substack);
for (int i = 0; i < 34; i++) {
set.Push(i);
}
for (int i = 0; i < 34; i++) {
System.out.println("Popped " + set.Pop());
}
}
}
class Link {
public int data;
public Link next;
public Link(int data) {
this.data = data;
}
}
class LinkList {
private Link first;
public LinkList() {
first = null;
}
public void ins(int id) {
Link a = new Link(id);
a.next = first;
first = a;
}
public int delFisrt() {
Link temp = first;
first = first.next;
return temp.data;
}
public boolean isEmpty() {
return (first == null);
}
}
class LinkStack {
public int size;
private int capacity;
private LinkList newList;
public LinkStack(int capacity) {
newList = new LinkList();
this.capacity = capacity;
size = 0;
}
public void push(int a) {
newList.ins(a);
size++;
}
public int pop() {
size--;
return newList.delFisrt();
}
public boolean isEmpty() {
return newList.isEmpty();
}
public boolean isFull() {
return (size == capacity);
}
}
class SetOfStacks {
ArrayList stacks = new ArrayList ();
private int capacity;
public SetOfStacks(int capacity) {
this.capacity = capacity;
}
private LinkStack getLastStack() {
if (stacks.size() == 0) {
return null;
}
return stacks.get(stacks.size()-1);
}
public void Push(int val) {
LinkStack last = getLastStack();
if (last != null && !last.isFull()) {
last.push(val);
} else {
LinkStack stack = new LinkStack(capacity);
stack.push(val);
stacks.add(stack);
}
}
public int Pop() {
LinkStack last = getLastStack();
int val = last.pop();
if (last.size == 0) {
stacks.remove(stacks.size() - 1);
}
return val;
}
}