当前位置: 首页 > news >正文

力扣刷题-热题100题-第31题(c++、python)

25. K 个一组翻转链表 - 力扣(LeetCode)https://leetcode.cn/problems/reverse-nodes-in-k-group/?envType=study-plan-v2&envId=top-100-liked

常规模拟

根据翻转的长度找到头和尾,进入函数进行翻转

主程序里有循环不断找到头和尾并拼接起来

//c++
/*** Definition for singly-linked list.* struct ListNode {*     int val;*     ListNode *next;*     ListNode() : val(0), next(nullptr) {}*     ListNode(int x) : val(x), next(nullptr) {}*     ListNode(int x, ListNode *next) : val(x), next(next) {}* };*/
class Solution {
public:pair<ListNode*,ListNode*> r(ListNode* head,ListNode* tail){ListNode* pre=tail->next;ListNode* a=head;while(pre!=tail){ListNode* nex=a->next;a->next=pre;pre=a;a=nex;}return {tail,head};}ListNode* reverseKGroup(ListNode* head, int k) {ListNode* h=new ListNode(0);ListNode* pre=h;h->next=head;while(head){ListNode* tail=pre;for(int i=0;i<k;i++){tail=tail->next;if(!tail)    return h->next;}ListNode* n=tail->next;tie(head,tail)=r(head,tail);pre->next=head;tail->next=n;pre=tail;head=tail->next;}return h->next;}
};#python
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:def reverseKGroup(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:def r(hh:ListNode,tail:ListNode):nex=tail.nexth1=hhwhile nex!=tail:h2=h1.nexth1.next=nexnex=h1h1=h2return tail,hhans=ListNode()ans.next=headpre=answhile pre.next:tail=prefor i in range(k):tail=tail.nextif tail==None:return ans.nexta=tail.nextaa,bb=r(pre.next,tail)pre.next=aabb.next=apre=bbreturn ans.next

这里是我的第一想法,比较愚蠢,直接用内存把地址存起来,然后倒序遍历去拼接,一点参考

#python
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:def reverseKGroup(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:ans=ListNode()pre=ansh=headwhile head:a=[]for i in range(k):if h==None:return ans.nexta.append(h)h=h.nexta.append(h)for i in range(-2,-k-2,-1):pre.next=a[i]pre=pre.nextpre.next=a[-1]return ans.next


http://www.mrgr.cn/news/97186.html

相关文章:

  • mysql and redis简化版
  • 虚幻5学习笔记,疑点
  • 八、重学C++—动态多态(运行期)
  • MySQL-SQL-DDL语句、表结构创建语句语法、表约束、表数据类型,表结构-查询SQL、修改SQL、删除SQL
  • 【Android】界面布局-线性布局LinearLayout-例子
  • Linux常用基础命令应用
  • 理解OSPF 特殊区域Stub和各类LSA特点
  • Android学习总结之算法篇四(排序)
  • Vite环境下解决跨域问题
  • 黑马点评redis改 part 1
  • 源支付开源全套,源支付V7开源全套,源支付V1.8.9,源支付开源版
  • Docker 命令简写配置
  • SpringAI整合Ollama集成DeepSeek
  • 图漾相机——C#语言属性设置
  • ✅ 2025最新 | YOLO 获取 COCO 指标终极指南 | 从标签转换到 COCOAPI 评估 (训练/验证) 全覆盖【B 站教程详解】
  • ARXML文件解析-1
  • Ubuntu安装Podman教程
  • MySQL 面试知识点详解(索引、存储引擎、事务与隔离级别、MVCC、锁机制、优化)
  • Git 教程:从 0 到 1 全面指南 教程【全文三万字保姆级详细讲解】
  • 第十二步:react