Description
Solution
题目要求: 常数额外空间 && 实际上的节点交换
先遍历一遍链表获取链表长度,再通过一次遍历进行节点交换
第二次遍历时, 将链表按 k 个一组分组, 记录下每组的第一个和最后一个
本质上就是把组内节点倒过来, 把前一组的第一个节点指向该组最后一个节点即可
具体实现细节见代码
时间复杂度:
O
(
N
)
O(N)
O(N)
空间复杂度:
O
(
1
)
O(1)
O(1)
Code
/**
* 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:
typedef ListNode* p;
ListNode* reverseKGroup(ListNode* head, int k) {
if(k == 1) return head;//特殊情况 不做任何改变
int tot = 0;
p now = head;
while(true) {
tot++;
if(now->next == nullptr) break;
now = now->next;
}
now = head;
int lim = tot - tot % k, id = 0, tim = 0;
p ng_fir = nullptr, pg_fir = nullptr, tmp = nullptr, pre = nullptr, res = head;
while(true) {
if(id == lim) {
ng_fir->next = now;
//连接剩余的节点
//剩余的节点保持原有顺序
break;
}
if(id % k == k - 1) {
// 该节点为本组最后一个
tim++;
if(res == head) res = now;//保存最终链表的头
if(pg_fir != nullptr && tim >= 2) pg_fir->next = now;//前一组第一个指向本组最后一个
}
tmp = now->next;
if((id++) % k != 0) now->next = pre;//不是最后一个,则指向前一个节点
else pg_fir = ng_fir,ng_fir = now;//该节点为本组第一个
pre = now;
now = tmp;
}
return res;
}
};