当前位置:网站首页>LeetCode 25:K个一组翻转链表
LeetCode 25:K个一组翻转链表
2022-06-21 16:02:00 【二芒星】
题目
给你一个链表,每 k 个节点一组进行翻转,请你返回翻转后的链表。
k 是一个正整数,它的值小于或等于链表的长度。
如果节点总数不是 k 的整数倍,那么请将最后剩余的节点保持原有顺序。
示例1
输入:head = [1,2,3,4,5], k = 2
输出:[2,1,4,3,5]
示例2
输入:head = [1,2,3,4,5], k = 3
输出:[3,2,1,4,5]
示例3
输入:head = [1,2,3,4,5], k = 1
输出:[1,2,3,4,5]
示例4
输入:head = [1], k = 1
输出:[1]
思路
主要分为两步:
- 首先判断节点是否够k个,若不到k个直接返回(break)
- k个节点翻转:
- 如
0->1->2->3->4,假设k=3,翻转1->2->3,先让该k节点内部翻转1<-2<-3然后让0->3,最后再让1->4,从而形成0->3->2->1->4,形成翻转
- 如
时间复杂度分析:O(n),对链表进行遍历一次O(n),还有两次遍历都是常量空间O(k)
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:
ListNode* reverseKGroup(ListNode* head, int k) {
auto dummy = new ListNode(-1);
dummy->next = head;
for (auto p = dummy; ; ) {
auto q = p;
/** 判断该点之后是否有k个元素 */
for (int i = 0; i < k && q; i ++) q = q->next;
if (!q) break; /* 不足k个元素直接返回 */
auto a = p->next, b = a->next;
for (int i = 0; i < k - 1; i ++) {
auto c = b->next;
b->next = a;
a = b, b = c;
}
auto c = p->next;
p->next = a, c->next = b;
p = c;
}
return dummy->next;
}
};
边栏推荐
- In 2021 database market, aerospike competes with top manufacturers
- Sword finger offer II 089 House theft / Sword finger offer II 090 Ring house theft
- [1108. IP address invalidation]
- 《网络是怎么样连接的》读书笔记 - FTTH
- 还在用 Xshell ?试试这款炫酷的 SSH 终端工具吧,功能很强大!
- Yaml data driven demo
- 未定义的函数或变量【一文讲透】(Matlab)
- 二叉树的序列化与反序列化
- qtcreator報錯解决
- 从北京“润”到芝加哥,工程师宝玉“滋润”成长的秘诀
猜你喜欢

The "learning link" database of the learning software is suspected to have leaked information, revealing more than 100million pieces of student information

为什么要做茶叶商城小程序app开发?

垃圾回收器

Test log of unittest framework

未定义的函数或变量【一文讲透】(Matlab)

Cloud native hybrid cloud network interconnection
![[ros2 basics] Introduction to navigation2 navigation system](/img/7f/ad6af972460d7a78fb28d9b4c24477.png)
[ros2 basics] Introduction to navigation2 navigation system

智能制造的下一站:云原生+边缘计算双轮驱动

I do 3D restoration for the aircraft carrier: these three details are shocking

NLog自定义Target之MQTT
随机推荐
设计一个打印整棵树的打印函数
【SQLite】解决unrecognized token:“‘“
UDP和TCP的对比
Notice on printing and distributing the Interim Measures of Beijing Municipality for the administration of housing with common property rights
Yaml data driven demo
D improve translation
第十六周总结
Oracle中实现获取指定行内容——Rownum和Row_number()
Publicity of the first batch of shortlisted enterprises! Annual Top100 smart network supplier selection
exness:美国通货膨胀影响太大,美联储大佬纷纷表态
模板:P6114 【模板】Lyndon 分解&Runs(字符串)
Qt 知识:使用 QGraphicsPixmapItem类
垃圾回收器
Fisher信息量检测对抗样本代码详解
Unittest框架
快来围观–TPT18新版报到
Cloud native monitoring system - Nightingale's recent list of new functions to solve multiple production pain points
Résolution des erreurs signalées par qtcreator
[theory] - interface test
容器云是什么意思?与堡垒机有什么区别?