Given a stack S, need to sort the stack using only Push, Pop, Top, IsEmpty, IsFull.
Looking for most sim
For this problem, can we consider using system stack? Make several recursive calls.
public static void sort(Stack s) {
if (!s.isEmpty()) {
Integer t = s.pop();
sort(s);
insert(t, s);
}
}
private static void insert(Integer x, Stack s) {
if (s.isEmpty()) {
s.push(x);
return;
}
if (x < s.peek()) {
Integer t = s.pop();
insert(x, s);
s.push(t);
} else {
s.push(x);
}
}