给你一个栈结构,请你逆序这个栈结构,不能申请额外的数据结构,只能使用递归函数,如何实现? 只能使用递归函数?
思路:无法使用额外的数据结构,也就只能借用函数栈来实现了;
1.首先实现一个函数,移除栈底元素并且返回;
private Integer removeAndReturnBottom(Stack<Integer> stack){
// 返回栈低元素
if(stack.size() == 1) {
return stack.pop();
}
Integer res;
// 如果不是栈底,弹出当前元素
int tmp = stack.pop();
// 递归调用移除栈底元素,并且返回栈底元素;
res = removeAndReturnBottom(stack);
// 再次压入当前元素
stack.push(tmp);
return res;
}
2.实现栈数据结构的逆序
private void reverseStack(Stack<Integer> stack) {
if(stack.isEmpty()) return;
// 获得当前栈底的元素
int bottom = removeAndReturnBottom(stack);
//递归调用逆序栈函数
reverseStack(stack);
// 压入当前栈底元素
stack.push(bottom);
}