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

每日两题 / 24. 两两交换链表中的节点 25. K 个一组翻转链表(LeetCode热题100)

24. 两两交换链表中的节点 - 力扣(LeetCode)
image.png

定义三个指针,交换前先保存ntnt指针为next->next,cur和next两个节点,然后将pre->next指向next
若pre为空,说明当前交换的节点为头两个节点,不需要修改pre->next
若cur不为空而next为空,则将pre->next指向cur
然后根据ntnt更新三个节点,当cur或者next为nullptr时,终止交换

/*** 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:ListNode* swapPairs(ListNode* head) {ListNode *pre = nullptr;ListNode *cur = head, *next = nullptr;if (cur) next = cur->next;if (next) head = next;while (next && cur){ListNode *ntnt = next->next;next->next = cur; cur->next = nullptr;if (pre) pre->next = next;pre = cur, cur = ntnt;if (cur) next = cur->next;}if (pre && cur && (next == nullptr)) pre->next = cur;return head;}
};

25. K 个一组翻转链表 - 力扣(LeetCode)
image.png

先统计俩表中节点的数量n,需要翻转(n / k)组链表
使用哨兵new_head作为伪头节点
记录上一次k组的尾节点,初始为new_head
翻转完一组节点,将尾节点的next指向刚才翻转一组节点的头节点
对于每组节点的翻转,使用三个指针,将pre->cur修改cur->pre,再用next更新两个指针(pre = cur,cur = next)
每个子链表需要翻转k - 1次,一共需要翻转n / k组
最后,若k不能整除n,那么将上一组节点的尾节点next指向剩下节点的头节点
若k能整除n,那么将上一组节点的尾节点next指向nullptr

/*** 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:ListNode* reverseKGroup(ListNode* head, int k) {int n = 0;ListNode *cur = head;while (cur){cur = cur->next;n ++ ;}ListNode *new_head = new ListNode;ListNode *pre = head;ListNode *hhead = nullptr, *tail = new_head;if (pre) cur = pre->next;for (int i = 0; i < n / k; ++ i){            ListNode *new_tail = pre;for (int j = 0; j < k - 1; ++ j){ListNode *next = cur->next;cur->next = pre;pre = cur, cur = next;}hhead = pre, tail->next = hhead, tail = new_tail;if (cur) pre = cur, cur = cur->next;}if (n % k) tail->next = pre;else tail->next = nullptr;return new_head->next;}
};
http://www.lryc.cn/news/345312.html

相关文章:

  • 【Linux】模拟实现bash(简易版)
  • C++ | Leetcode C++题解之第67题二进制求和
  • 如何确保UDP文件传输工具有最低稳定的传输速度?
  • 力扣爆刷第133天之动态规划收尾(距离编辑与回文子串)
  • List集合中对asList的使用
  • 软件测试所有测试方法
  • linux 下 /usr/local的作用
  • 【web网页制作】html+css旅游家乡河南开封主题网页制作(4页面)【附源码】
  • MySQL用命令行导出数据库
  • uniapp video 层级覆盖
  • SparkSQL概述
  • docker 和 docker-compose
  • 微信小程序支付(完整版)-ThinkPHP/Uniapp
  • 同时安装多个nodejs版本可切换使用,或者用nvm管理、切换nodejs版本(两个详细方法)
  • 马化腾用了一年多的时间,告诉所有人,视频号小店是新风口!
  • 代码随想录算法训练营第36期DAY19
  • C#图像:1.图像区域分割与提取
  • 炸弹使用技巧
  • SpringAop详解
  • 对XYctf的一些总结
  • Visual Studio和Visual Studio Code适用于哪些编程语言
  • 缓存菜品操作
  • 达梦数据库常用命令整理
  • Vue 组件的三大组成部分
  • MoneyPrinter中的文字转声音国内替换方案
  • 消除试卷手写笔迹的软件免费的有哪些?这几款都不错
  • 智能创作时代:AI 如何重塑内容生成游戏规则
  • 大数据------JavaWeb------Tomcat(完整知识点汇总)
  • LMDeploy笔记
  • Unity 状态机