如何仅用递归函数和栈操作逆序一个栈(不用额外空间)
程序员文章站
2024-02-27 22:59:51
...
int getStackBottomDate(Stack<Integer> stack) {
int result = stack.pop();
if (stack.isEmpty()) {
return result;
} else {
int last = getStackBottomDate(stack);
stack.push(result);
return last;
}
}
void reverseStack(Stack<Integer> stack) {
if (stack.isEmpty()) {
return;
}
int res = getStackBottomDate(stack);
reverseStack(stack);
stack.push(res);
}