Monday, July 19, 2021

LintCode 229 · Stack Sorting.java

public class Solution {
/*
* @param stk: an integer stack
* @return: void
*/
public void stackSorting(Stack<Integer> stk) {
// write your code here
if (stk == null || stk.size() < 2) {
return ;
}
// fill the holderStack in reverse order
Stack<Integer> holderStack = new Stack<>();
while (!stk.isEmpty()) {
Integer latest = stk.pop();
if (holderStack.isEmpty()) {
holderStack.push(latest);
} else {
while (!holderStack.isEmpty() && holderStack.peek() < latest) {
stk.push(holderStack.pop());
}
holderStack.push(latest);
}
}
// fill the original stack in regular order.
while (!holderStack.isEmpty()) {
stk.push(holderStack.pop());
}
return ;
}
}

No comments:

Post a Comment