反转栈
来源:互联网 发布:linux 关闭图形界面 编辑:程序博客网 时间:2024/06/04 10:07
给定一个堆栈【1, 2, 3】,反转为【3, 2, 1】
import java.util.Stack;public class ReverseStack {<span style="white-space:pre"></span>public static void main(String[] args) {<span style="white-space:pre"></span>Stack<Integer> stack = new Stack<Integer>();<span style="white-space:pre"></span>for (int i = 0; i < 10; i++) {<span style="white-space:pre"></span>stack.push(i);<span style="white-space:pre"></span>}<span style="white-space:pre"></span>print(stack);<span style="white-space:pre"></span>reverse(stack);<span style="white-space:pre"></span>print(stack);<span style="white-space:pre"></span>}<span style="white-space:pre"></span>public static void print(Stack<Integer> stack) {<span style="white-space:pre"></span>System.out.print("[");<span style="white-space:pre"></span>for (int i : stack) {<span style="white-space:pre"></span>System.out.print(i + " ");<span style="white-space:pre"></span>}<span style="white-space:pre"></span>System.out.println("]");<span style="white-space:pre"></span>}<span style="white-space:pre"></span>public static void reverse(Stack<Integer> stack) {<span style="white-space:pre"></span>if (!stack.isEmpty()) {<span style="white-space:pre"></span>int i = stack.pop();<span style="white-space:pre"></span>reverse(stack);<span style="white-space:pre"></span>// add the<span style="white-space:pre"></span>addBottom(stack, i);<span style="white-space:pre"></span>}<span style="white-space:pre"></span>}<span style="white-space:pre"></span>private static void addBottom(Stack<Integer> stack, int i) {<span style="white-space:pre"></span>if (stack.isEmpty()) {<span style="white-space:pre"></span>stack.push(i);<span style="white-space:pre"></span>} else {<span style="white-space:pre"></span>int e = stack.pop();<span style="white-space:pre"></span>addBottom(stack, i);<span style="white-space:pre"></span>stack.push(e);<span style="white-space:pre"></span>}<span style="white-space:pre"></span>}}
0 0
- 反转栈
- 使用栈反转字符串
- Java反转一个栈
- 反转一个栈
- 递归反转一个栈
- 栈的反转
- 栈_数列反转
- 栈的反转
- 栈的反转练习题
- 栈的反转练习
- 栈的反转
- 栈的反转
- 反转
- java实现栈的反转
- 递归地反转一个栈
- 使用递归反转一个栈
- 数据结构--栈的反转练习题
- 栈(stack) 实现字符串反转
- 74138集成电路译码器
- Android获取Toast的String解析
- C++ 指向函数的指针
- MFC listBox 某一项数据显示不同的颜色
- mod_jk(Apache+mod_jk+tomcat)详细配置方法
- 反转栈
- 三消游戏FSM状态机设计图
- 深入理解Android系列书籍资源分享更新
- JQuery实现图片切换(自动切换+手动切换)
- docker 容器相关命令
- 给菜单配置小图标
- 开始Linux之路
- ZOJ 1003 Crashing Balloon
- POJ 1306 Combinations (二项式系数公式求组合数)