力扣 简单 206.反转链表

文章目录

题目介绍

题解

法一:双指针
在遍历链表时,将当前节点的 next 改为指向前一个节点。由于节点没有引用其前一个节点,因此必须事先存储其前一个节点。在更改引用之前,还需要存储后一个节点。最后返回新的头引用。

代码如下:

java 复制代码
class Solution {
    public ListNode reverseList(ListNode head) {
        ListNode pre = null, cur = head;
        while (cur != null) {
            ListNode nxt = cur.next;
            cur.next = pre;
            pre = cur;
            cur = nxt;
        }
        return pre;
    }
}

法二:递归

java 复制代码
/**
 * 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 reverseList(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode newHead = reverseList(head.next);
        head.next.next = head;
        head.next = null;
        return newHead;
    }
}
相关推荐
lUie INGA5 小时前
在2023idea中如何创建SpringBoot
java·spring boot·后端
geBR OTTE5 小时前
SpringBoot中整合ONLYOFFICE在线编辑
java·spring boot·后端
Porunarufu5 小时前
博客系统UI自动化测试报告
java
不爱吃炸鸡柳6 小时前
数据结构精讲:树 → 二叉树 → 堆 从入门到实战
开发语言·数据结构
Aurorar0rua6 小时前
CS50 x 2024 Notes C - 05
java·c语言·数据结构
Cosmoshhhyyy7 小时前
《Effective Java》解读第49条:检查参数的有效性
java·开发语言
布谷歌7 小时前
常见的OOM错误 ( OutOfMemoryError全类型详解)
java·开发语言
6Hzlia7 小时前
【Hot 100 刷题计划】 LeetCode 739. 每日温度 | C++ 逆序单调栈
c++·算法·leetcode
eLIN TECE7 小时前
springboot和springframework版本依赖关系
java·spring boot·后端