欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 科技 > 名人名企 > 力扣--LCR 141.训练计划III

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

2025/3/13 18:57:34 来源:https://blog.csdn.net/weixin_52297290/article/details/143968123  浏览:    关键词:力扣--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),递归调用需要消耗栈空间

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词