java实现 链表反转
输入一个链表,反转链表后,输出新链表的表头。
递归法
public class RevnNode { public static class Node { public int value; public Node nextNode; public int getValue() { return value; } public void setValue(int value) { this.value = value; } public Node getNextNode() { return nextNode; } public void setNextNode(Node nextNode) { this.nextNode = nextNode; } public Node(int value) { this.value = value; } } /** * 反转操作方法1 递归实现:从最后一个Node开始,在弹栈的过程中将指针顺序置换的。 * * @param head * @return */ public static Node reverse1(Node head) { if (head == null || head.nextNode == null) return head; Node temp = head.nextNode; Node newHead = reverse1(head.nextNode); temp.nextNode = head; head.nextNode = null; return newHead; } /** * 反转操作方法2 :在链表遍历的过程中将指针顺序置换 * @param node * @return */ public static Node reverse2(Node node) { Node pre = null; Node next = null; while (node != null) { next = node.nextNode; node.nextNode = pre; pre = node; node = next; } return pre; } public static void main(String[] args) { Node head = new Node(0); Node node1 = new Node(1); Node node2 = new Node(2); Node node3 = new Node(3); head.setNextNode(node1); node1.setNextNode(node2); node2.setNextNode(node3); // 打印反转前的链表 Node h = head; while (null != h) { System.out.print(h.getValue() + " "); h = h.getNextNode(); } // 调用反转方法1 System.out.println("\n*********** reverse1 ***************"); head = reverse1(head); // 打印反转后的结果 while (null != head) { System.out.print(head.getValue() + " "); head = head.getNextNode(); } // 调用反转方法2 System.out.println("\n*********** reverse2 ***************"); head = reverse2(head); // 打印反转后的结果 while (null != head) { System.out.print(head.getValue() + " "); head = head.getNextNode(); } } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
2014-03-05 Android 学习 之 无需类名启动其他程序
2014-03-05 android xml文件中出现如下提醒:This tag and its children can be replaced by one <TextView/> and a compound drawable