【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;
        }
    }
}
相关推荐
Dream it possible!33 分钟前
LeetCode 面试经典 150_二分查找_在排序数组中查找元素的第一个和最后一个位置(115_34_C++_中等)
c++·leetcode·面试
小六子成长记2 小时前
【C++】:搜索二叉树的模拟实现
数据结构·c++·算法
汉克老师2 小时前
GESP2025年9月认证C++二级真题与解析(编程题1(优美的数字))
c++·算法·整除·枚举算法·求余·拆数
Zevalin爱灰灰3 小时前
现代控制理论——第二章 系统状态空间表达式的解
线性代数·算法·现代控制
菜鸟233号3 小时前
力扣377 组合总和 Ⅳ java实现
java·数据结构·算法·leetcode
我是大咖3 小时前
二级指针与指针数组搭配
c语言·数据结构·算法
老鼠只爱大米3 小时前
LeetCode算法题详解 189:轮转数组
leetcode·轮转数组·数组旋转·环状替换法·算法面试题
葫三生4 小时前
三生原理范畴语法表明中国哲学可为算法母语
人工智能·深度学习·算法·transformer
D_FW4 小时前
数据结构第五章:树与二叉树
数据结构·算法
WHS-_-20224 小时前
Tx and Rx IQ Imbalance Compensation for JCAS in 5G NR
javascript·算法·5g