【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;
        }
    }
}
相关推荐
米粒12 分钟前
力扣算法刷题 Day 24
算法·leetcode·职场和发展
郝学胜-神的一滴3 分钟前
从线程栈到表达式求值:栈结构的核心应用与递归实现
开发语言·数据结构·c++·算法·面试·职场和发展·软件工程
月落归舟3 分钟前
排序算法---(二)
数据结构·算法·排序算法
sonnet-10297 分钟前
交换排序算法
java·c语言·开发语言·数据结构·笔记·算法·排序算法
穿条秋裤到处跑11 分钟前
每日一道leetcode(2026.03.27):循环移位后的矩阵相似检查
算法·leetcode·矩阵
Cathy Bryant12 分钟前
拓扑学-毛球定理
笔记·线性代数·算法·矩阵·拓扑学·高等数学
2301_7887705513 分钟前
模拟OJ3
数据结构·算法
靠沿13 分钟前
【递归、搜索与回溯算法】专题二——二叉树的dfs
算法·深度优先
美式请加冰20 分钟前
BFS算法的介绍和使用(上)
算法·宽度优先
sonnet-102926 分钟前
堆排序算法
java·c语言·开发语言·数据结构·python·算法·排序算法