【算法】【线性表】【链表】反转链表
1 题目
给你单链表的头节点 head
,请你反转链表,并返回反转后的链表。
示例 1:
输入:head = [1,2,3,4,5]
输出:[5,4,3,2,1]
示例 2:
示例 3:
输入:head = []
输出:[]
提示:
- 链表中节点的数目范围是
[0, 5000]
-5000 <= Node.val <= 5000
2 解答
/** * Definition for ListNode * public class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */ public class Solution { /** * @param head: n * @return: The new head of reversed linked list. */ public ListNode reverse(ListNode head) { // write your code here ListNode resHead = new ListNode(head.val); while (head.next != null) { head = head.next; // 新建节点保存当前节点信息 ListNode node = new ListNode(head.val); // 把当前节点的下一个节点指向头节点 node.next = resHead; // 头节点指向当前新节点 resHead = node; } return resHead; } }
上边的空间相当于又创建了一份新的,再来个不产生新空间的头插法:
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode() {} * ListNode(int val) { this.val = val; } * ListNode(int val, ListNode next) { this.val = val; this.next = next; } * } */ class Solution { public ListNode reverse(ListNode head) { // 参数校验 if (head == null || head.next == null) { return head; } // 采用头插法进行插入 ListNode preNode = new ListNode(0); preNode.next = head; while (head.next != null) { ListNode nextNode = head.next; head.next = nextNode.next; nextNode.next = preNode.next; preNode.next = nextNode; } return preNode.next; } }
加油。
加油。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· Obsidian + DeepSeek:免费 AI 助力你的知识管理,让你的笔记飞起来!
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了