如何不使用额外的栈来逆序一个栈?


import java.util.Stack;

public class StackReverse {
//翻转栈
public static void reverse(Stack<Integer> stack) {
if (stack.isEmpty()) {
return;
}
int i = getAndRemoveLastElement(stack);
reverse(stack);
stack.push(i);
}
//利用递归得到并删掉最后一个值,作用是把栈底的值取出来并且删掉,栈空出一个位置,为压栈腾位置
public static int getAndRemoveLastElement(Stack<Integer> stack) {
int result = stack.pop();
if (stack.isEmpty()) {
return result;
} else {
int last = getAndRemoveLastElement(stack);
//在得到 last 后,会从当前的result逐步递归回第一个result
//需要执行完完整的方法,所以不是只压入一个result,压入的result的个数是stack中元素的个数减1
stack.push(result);
return last;
}
}

public static void main(String[] args) {
Stack<Integer> test = new Stack<Integer>();
test.push(1);
test.push(2);
test.push(3);
test.push(4);
test.push(5);
reverse(test);
while (!test.isEmpty()) {
System.out.println(test.pop());
}
}
}

优质内容筛选与推荐>>
1、Allocate exception for servlet XFireServlet 找不到 Org.apache.xbean.spring.context.SpringApplicationContext;
2、持续改进中, Gnome Shell 2.91.3 发布
3、Java零基础学习(三)封装继承多态
4、Mysql中随机函数笔记
5、【265】shell文件创建链接


长按二维码向我转账

受苹果公司新规定影响,微信 iOS 版的赞赏功能被关闭,可通过二维码转账支持公众号。

    阅读
    好看
    已推荐到看一看
    你的朋友可以在“发现”-“看一看”看到你认为好看的文章。
    已取消,“好看”想法已同步删除
    已推荐到看一看 和朋友分享想法
    最多200字,当前共 发送

    已发送

    朋友将在看一看看到

    确定
    分享你的想法...
    取消

    分享想法到看一看

    确定
    最多200字,当前共

    发送中

    网络异常,请稍后重试

    微信扫一扫
    关注该公众号