请设计一个算法实现逆序 栈的操作

请设计一个算法实现逆序 栈的操作

一个栈依次压入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]


import java.util.*;
public class ReverseStack {
public int[] reverseStackRecursively(int[] stack, int top) {
// write code here
int result[]=new int[top];
return help(stack,top-1,result,-1);
}
public int[] help(int[] stack,int top,int[] result,int top2){
int temp=stack[top];
result[top2+1]=temp;
if(top!=0){
help(stack,top-1,result,top2+1);
}
return result;
}
}

猜你喜欢

转载自blog.csdn.net/pigdwh/article/details/82056326
今日推荐