1、如何仅用递归函数和栈操作逆序一个栈
一个栈依次入栈顺序为12345,从栈顶到栈底是54321,若要从栈顶到栈底是12345,即逆序,怎么做,只能用递归函数,不能用其他数据结构
public static void reverse(Stack<Integer> stack){
if(stack.isEmpty()){
return;
}
int i = getAndRemoveLastElement(stack);//依次获取1、2、3
reverse(stack);//递归
stack.push(i);//依次压入3、2、1
}
//如果栈顶到栈底是321,则功能是返回1,1不压入,23会重新压入
public static int getAndRemoveLastElement(Stack<Integer> stack){
int result = stack.pop();
if(stack.isEmpty()){
return result;//栈为空时返回栈底元素,但是不压入栈
}else{
int last = getAndRemoveLastElement(stack);//递归,一直到最后一个
stack.push(result);//如果不是栈底的话,就压入
return last;
}
}
2、用一个栈实现另一个栈的排序
将一个栈从栈顶到栈底按照从大到小的顺序排序,只允许用一个辅助栈
/*
* 如果cur<=help.peek(),则将cur压入help
* 如果cur大于help.peek(),则将help的元素一一弹出,逐一压入stack中,直到cur<=help.peek(),再将cur压入到help
*/
public static void sortStackByStack(Stack<Integer> stack){
Stack<Integer> help = new Stack<Integer>();
while(!stack.isEmpty()){
int cur = stack.pop();
while(!help.isEmpty() && help.peek()>cur){
stack.push(help.pop());//比cur大的都返回stack中
}
help.push(cur);
}
//按从大到小的顺序
while(!help.isEmpty()){
stack.push(help.pop());
}
}