一个栈依次压入1,2,3,4,5那么从栈顶到栈底分别为5,4,3,2,1。将这个栈转置后,从栈顶到栈底为1,2,3,4,5,也就是实现了栈中元素的逆序,请设计一个算法实现逆序栈的操作,但是只能用递归函数来实现,而不能用另外的数据结构。
给定一个栈Stack以及栈的大小top,请返回逆序后的栈。
测试样例:
[1,2,3,4,5],5
返回:[5,4,3,2,1]
kevinLee523
public int[] reverseStackRecursively(int[] stack, int top) {
if(top <= stack.length / 2) {
return stack;
}
int x = top;
int[] newStack = reverseStackRecursively(stack, --x);
int index = newStack.length - top;
int temp = 0;
temp = newStack[index];
newStack[index] = newStack[top-1];
stack[top-1] = temp;
return newStack;
} import java.util.*;
public class ReverseStack {
public int getBottom(int[] stack,int top){
if(top==1)
return stack[top-1];
else{
int tmp=stack[top-1];
top--;
int bottom=getBottom(stack,top);
stack[top-1]=tmp;
top++;
return bottom;
}
}
public int[] reverseStackRecursively(int[] stack, int top) {
if(top<1){
return stack;
}
else{
int bottom=getBottom(stack,top--);
stack=reverseStackRecursively(stack, top);
stack[top++]=bottom;
return stack;
}
}
}