【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;
        }
    }
}
相关推荐
梵刹古音13 分钟前
【C语言】 字符数组相关库函数
c语言·开发语言·算法
wfeqhfxz25887827 小时前
YOLO13-C3k2-GhostDynamicConv烟雾检测算法实现与优化
人工智能·算法·计算机视觉
Aaron15887 小时前
基于RFSOC的数字射频存储技术应用分析
c语言·人工智能·驱动开发·算法·fpga开发·硬件工程·信号处理
_不会dp不改名_9 小时前
leetcode_3010 将数组分成最小总代价的子数组 I
算法·leetcode·职场和发展
你撅嘴真丑11 小时前
字符环 与 变换的矩阵
算法
早点睡觉好了11 小时前
重排序 (Re-ranking) 算法详解
算法·ai·rag
gihigo199811 小时前
基于全局自适应动态规划(GADP)的MATLAB实现方案
算法
ctyshr12 小时前
C++编译期数学计算
开发语言·c++·算法
zh_xuan12 小时前
最小跳跃次数
数据结构·算法
yumgpkpm12 小时前
2026软件:白嫖,开源,外包,招标,晚进场(2025年下半年),数科,AI...中国的企业软件产业出路
大数据·人工智能·hadoop·算法·kafka·开源·cloudera