LeetCode 206. 反转链表

题目描述


分析

迭代代码与之前的K个一组翻转链表相同。

递归代码的一个首要任务是找到整个链表的尾结点(反转后的头结点)。

之后一步一步地将tail结点向前返回,但在返回的过程中不利用,只是传递最终答案。绿线的操作就是当head为正数第一个结点时的调用情况。

grq:递归的做法记得要将当前调用的head的指向置null,否则会出现链表中出现环的情况。


迭代代码(Java)
java 复制代码
class Solution {
    public ListNode reverseList(ListNode head) {
        if (head == null) return head;
        ListNode dummy = new ListNode(-1);
        dummy.next = head;
        ListNode first = head, second = first.next;
        // 若second为null说明当前的first是尾结点
        while (second != null) {
            ListNode secondNext = second.next;
            // 将后一位指向前一位
            second.next = first;
            // 两个指针后移,之后新增第三个指针
            first = second;
            second = secondNext;
        }
        dummy.next.next = null;
        dummy.next = first;
        return dummy.next;
    }
}
递归代码(Java)
java 复制代码
class Solution {
    public ListNode reverseList(ListNode head) {
	    // 判断到head.next为null就是尾结点
        if (head == null || head.next == null) return head;
        // 递归找到尾结点,保存用于反转后的头结点
        ListNode tail = reverseList(head.next);
        // 第一次是更改尾结点指向倒数第二个结点
        // 这里的head是倒数第二个结点
        head.next.next = head;
        // 将null转递下去,初始的头结点指向
        head.next = null;
        return tail;
    }
}
相关推荐
曾几何时`1 天前
MySQL(四)表的约束
算法
gihigo19981 天前
竞争性自适应重加权算法
人工智能·算法·机器学习
明洞日记1 天前
【CUDA手册004】一个典型算子的 CUDA 化完整流程
c++·图像处理·算法·ai·图形渲染·gpu·cuda
金色光环1 天前
【SCPI学习】STM32与LWIP实现SCPI命令解析
stm32·嵌入式硬件·算法·scpi学习·scpi
豆沙沙包?1 天前
2026年--Lc342-841. 钥匙和房间(图 - 广度优先搜索)--java版
java·算法·宽度优先
Emilin Amy1 天前
【C++】【STL算法】那些STL算法替代的循环
开发语言·c++·算法·ros1/2
Hcoco_me1 天前
大模型面试题74:在使用GRPO训练LLM时,训练数据有什么要求?
人工智能·深度学习·算法·机器学习·chatgpt·机器人
天赐学c语言1 天前
1.16 - 二叉树的中序遍历 && 动态多态的实现原理
数据结构·c++·算法·leecode
sin_hielo1 天前
leetcode 2975
数据结构·算法·leetcode
java修仙传1 天前
力扣hot100:跳跃游戏
算法·leetcode·游戏