力扣--LCR 141.训练计划III

题目

给定一个头节点为 head 的单链表用于记录一系列核心肌群训练编号,请将该系列训练编号 倒序 记录于链表并返回。

示例 1:

输入:head = [1,2,3,4,5]

输出:[5,4,3,2,1]

示例 2:

输入:head = [1,2]

输出:[2,1]

示例 3:

输入:head = []

输出:[]

提示:

复制代码
链表中节点的数目范围是 [0, 5000]
-5000 <= Node.val <= 5000

代码

/**

  • Definition for singly-linked list.

  • public class ListNode {

复制代码
  int val;
复制代码
  ListNode next;
复制代码
  ListNode() {}
复制代码
  ListNode(int val) { this.val = val; }
复制代码
  ListNode(int val, ListNode next) { this.val = val; this.next = next; }
  • }

    */

    class Solution {

    public ListNode trainningPlan(ListNode head) {

    if(headnull||head.nextnull){

    return head;

    }

    ListNode cur = head, pre = null;

    复制代码
     while(cur != null){
         ListNode temp = cur.next;
         cur.next = pre;
         pre = cur;
         cur = temp;
     }
    
     return pre;

    }

    }

    时间复杂度:O(N)

    额外空间复杂度 O(1)

递归

// 递归

public ListNode reverseList(ListNode head) {

if(head == null || head.next == null){

return head;

}

// 反转子链表

ListNode temp = reverseList(head.next);

head.next.next = head;

head.next = null;

复制代码
    return temp;
}

时间复杂度:O(N)

额外空间复杂度 O(n),递归调用需要消耗栈空间

相关推荐
tankeven2 小时前
动态规划专题(03):区间动态规划从原理到实践(未完待续)
c++·算法·动态规划
田梓燊3 小时前
2026/4/11 leetcode 3741
数据结构·算法·leetcode
斯内科3 小时前
FFT快速傅里叶变换
算法·fft
2301_822703203 小时前
开源鸿蒙跨平台Flutter开发:幼儿疫苗全生命周期追踪系统:基于 Flutter 的免疫接种档案与状态机设计
算法·flutter·华为·开源·harmonyos·鸿蒙
贵慜_Derek3 小时前
Managed Agents 里,Harness 到底升级了什么?
人工智能·算法·架构
2301_822703204 小时前
鸿蒙flutter三方库实战——教育与学习平台:Flutter Markdown
学习·算法·flutter·华为·harmonyos·鸿蒙
Jia ming4 小时前
C语言实现日期天数计算
c语言·开发语言·算法
无限进步_4 小时前
【C++&string】大数相乘算法详解:从字符串加法到乘法实现
java·开发语言·c++·git·算法·github·visual studio
苏纪云5 小时前
蓝桥杯考前突击
c++·算法·蓝桥杯
W23035765735 小时前
经典算法详解:最长公共子序列 (LCS) —— 从暴力递归到动态规划完整实现
算法·动态规划·最长子序列