如何仅用递归函数和栈逆序一个栈
/**
* 获取栈底元素
*
* @param stack 传入的栈
* @param <E> 返回的元素类型
* @return 栈底元素
*/
private static <E> E getAndRemoveLastElement(Stack<E> stack) {
E result = stack.pop();
if (stack.isEmpty()) {
return result;
} else {
E last = getAndRemoveLastElement(stack);
stack.push(result);
return last;
}
}
getAndRemoveLastElement
方法
/**
* 逆序一个栈
*
* @param stack 被操作的栈
* @param <E> 栈中元素类型
*/
public static <E> void reverse(Stack<E> stack) {
if (stack.isEmpty()) {
return;
}
E element = getAndRemoveLastElement(stack);
reverse(stack);
stack.push(element);
}
public class Main {
public static void main(String[] args) {
Stack<Integer> testStack = new Stack<>();
for (int i = 1; i <= 5; i++) {
testStack.push(i);
}
StackReverseUtil.reverse(testStack);
}
}
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有