【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;
        }
    }
}
相关推荐
自信1504130575925 分钟前
初学者小白复盘15之指针(4)
c语言·数据结构·算法
郝学胜-神的一滴26 分钟前
Cesium绘制线:从基础到高级技巧
前端·javascript·程序人生·线性代数·算法·矩阵·图形渲染
东皇太星1 小时前
机器学习概念,算法原理及应用
算法·机器学习·梯度下降法
.格子衫.1 小时前
021数据结构之并查集——算法备赛
数据结构·算法
im_AMBER1 小时前
Leetcode 35
笔记·学习·算法·leetcode
码农多耕地呗1 小时前
力扣101.对称二叉树(java)
算法·leetcode
小龙报2 小时前
《算法通关指南之C++编程篇(5)----- 条件判断与循环(下)》
c语言·开发语言·c++·算法·visualstudio·学习方法·visual studio
郝学胜-神的一滴2 小时前
C++ STL(标准模板库)深度解析:从基础到实践
linux·服务器·开发语言·c++·算法
刚入坑的新人编程2 小时前
算法训练.17
开发语言·数据结构·c++·算法
白羊无名小猪2 小时前
排序算法总结
算法·排序算法