【Hot100】LeetCode—206. 反转链表

目录

  • [1- 思路](#1- 思路)
  • [2- 实现](#2- 实现)
    • [⭐206. 反转链表------题解思路](#⭐206. 反转链表——题解思路)
  • [3- ACM 实现](#3- ACM 实现)


1- 思路

递归法

  • 递归三部曲
    • ①终止条件 :遇到 head ==null || head.next==null 的时候
    • ②递归逻辑 :定义 curcur 执行递归逻辑,也就是调用 当前reverse(cur.next)
      • head.next.next = head;
      • head.next = null;

2- 实现

⭐206. 反转链表------题解思路

java 复制代码
class Solution {
    public ListNode reverseList(ListNode head) {
        if(head == null || head.next==null){
            return head;
        }
        // 递归
        ListNode cur = reverseList(head.next);
        head.next.next = head;
        head.next = null;
        return cur;
    }
}

3- ACM 实现

java 复制代码
public class reverseList {



    public static class ListNode {
        int val;
        ListNode next;
        ListNode(int x) {
            val = x;
            next = null;
        }
    }

    public static ListNode reverseList(ListNode head){
        if(head == null|| head.next == null){
            return head;
        }
        ListNode cur = reverseList(head.next);
        head.next.next = head;
        head.next = null;
        return cur;
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("输入链表长度");
        int n = sc.nextInt();
        ListNode head = null,tail=null;
        for(int i = 0 ; i < n;i++){
            ListNode nowNode  = new ListNode(sc.nextInt());
            if(head==null){
                head = nowNode;
                tail = nowNode;
            }else{
                tail.next = nowNode;
                tail = nowNode;
            }
        }
        ListNode forRes = reverseList(head);
        while(forRes!=null){
            System.out.print(forRes.val+" ");
            forRes = forRes.next;
        }
    }
}
相关推荐
alphaTao15 小时前
LeetCode 每日一题 2026/5/25-2026/5/31
算法·leetcode
菜菜的顾清寒15 小时前
力扣HOT100(41)动态规划-杨辉三角
算法·leetcode·动态规划
Cthy_hy15 小时前
Python算法竞赛:集合去重+字典映射 核心用法一站式整理
数据结构·python·算法
Deepoch15 小时前
Deepoc数学大模型:驱动发动机行业数智化转型的底层解
人工智能·算法·deepoc·数学大模型
happymaker062615 小时前
LeetCodeHot100——盛水最多的容器
数据结构·算法·leetcode·双指针·hot100
3DVisionary15 小时前
蓝光三维扫描:磁性轴承全尺寸精密3D检测方案
算法·3d·3d检测·蓝光三维扫描·精密检测·磁性轴承·圆度测量
过期动态15 小时前
【LeetCode 热题 100】三数之和
java·数据结构·算法·leetcode·职场和发展·排序算法
逻辑君15 小时前
Foresight研究报告【20260010】
人工智能·算法·机器学习
weixin_4684668515 小时前
大语言模型原理新手入门指南
人工智能·python·算法·语言模型·自然语言处理·transformer·注意力机制
z2005093015 小时前
今日算法(回溯找IP,加检测)
算法·leetcode