【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;
        }
    }
}
相关推荐
_fairyland26 分钟前
数据结构 力扣 练习
数据结构·考研·算法·leetcode
Neil今天也要学习44 分钟前
永磁同步电机无速度算法--基于三阶LESO的反电动势观测器
算法·1024程序员节
机器学习之心1 小时前
NGO-VMD北方苍鹰算法优化变分模态分解+皮尔逊系数+小波阈值降噪+信号重构,MATLAB代码
算法·matlab·重构·信号重构·ngo-vmd·皮尔逊系数·小波阈值降噪
橘颂TA1 小时前
【剑斩OFFER】算法的暴力美学——山脉数组的蜂顶索引
算法·leetcode·职场和发展·c/c++
速易达网络1 小时前
C语言常见推理题
java·c语言·算法
沪漂的码农1 小时前
C语言队列与链表结合应用完整指南
c语言·链表
freedom_1024_1 小时前
LRU缓存淘汰算法详解与C++实现
c++·算法·缓存
博语小屋2 小时前
力扣11.盛水最多的容器(medium)
算法·leetcode·职场和发展
Swift社区2 小时前
LeetCode 423 - 从英文中重建数字
算法·leetcode·职场和发展
点云SLAM2 小时前
算法与数据结构之二叉树(Binary Tree)
数据结构·算法·二叉树·深度优先·广度优先·宽度优先