Java实现链表反转(借助栈实现)
2024-09-01 12:23:30
public class ListNode {
int val;
ListNode next = null; ListNode(int val) {
this.val = val;
} // 添加新的结点
public void add(int newval) {
ListNode newNode = new ListNode(newval);
if (this.next == null)
this.next = newNode;
else
this.next.add(newval);
} // 打印链表
public void print() {
System.out.print(this.val);
if (this.next != null) {
System.out.print("-->");
this.next.print();
} }
}
import java.util.Stack; public class ListReverse {
public ListNode ReverseList(ListNode head) {
Stack<ListNode> stack = new Stack<ListNode>();
ListNode node = head;
if (head == null) {
return null;
}
while (node != null) {
stack.push(node);
node = node.next;
}
ListNode newHead = new ListNode(stack.pop().val);
ListNode tmp = newHead;
while (stack.size() > 0) {
node = stack.pop();
ListNode newtmp = new ListNode(node.val);
tmp.next = newtmp;
tmp = newtmp;
}
return newHead; // 在最后添加上null作为结束标志
} public static void main(String[] args) {
ListNode l1 = null; // 创建链表对象 l1 (对应有参 和 无参 构造方法)
if (l1 != null) {
l1.print();
ListReverse lr = new ListReverse();
ListNode reverseList = lr.ReverseList(l1);
System.out.println();
reverseList.print();
}else{ } }
}
最新文章
- ajax删除DB数据
- JS函数的上下文环境
- jQuery和JS原生方法对比
- 【JSON 注解】JSON循环引用2----JSON注解@JsonIgnoreProperties+JAVA关键字transient+后台对象与JSON数据的格式互相转化
- PHP iconv()函数转字符编码的问题(转)
- 使用json格式的数据进行通信
- C++_归并排序(纯C版)
- Java下拼接运行动态SQL语句
- sgu 104 Little Shop of Flowers
- cx_Oracle ORA-24315: 非法的属性类型的解决办法
- POJ2236 Wireless Network 并查集
- 工厂方法模式 - OK
- [Q]图框识别问题
- 启动ipython notebook(jupyter)
- SQL server 数据库(视图、事物、分离附加、备份还原))
- 咦,好像可以自己做个webapi框架了-IRouteHandler的使用
- 有史以来功能最全,使用最简单的excel导入/导出工具
- Spark:相关错误总结
- Day7 子类调用父类的方法supper 绑定方法与非绑定方法
- C#类继承中构造函数的执行序列
热门文章
- 【论文考古】量化SGD QSGD: Communication-Efficient SGD via Gradient Quantization and Encoding
- Flutter ChartSpace:通过跨端 Canvas 实现图表库
- 浅谈 SOLID 原则
- CF1106F题解
- 1、如何抓取Modbus TCP/UDP 数据包实战
- Python之GUI用户界面Tkinter(一)
- 无法更新apt镜像源?树莓派安装最新版Debian11(bullseye)arm64位系统步骤
- K8S搭建自动化部署环境 Jenkins下载、安装和启动
- 安装配置Snort和barnyard2
- 10ISE14.7和modelsim10.5关联编译库