25. K 个一组翻转链表
给你链表的头节点 head ,每 k 个节点一组进行翻转,请你返回修改后的链表。
k 是一个正整数,它的值小于或等于链表的长度。如果节点总数不是 k 的整数倍,那么请将最后剩余的节点保持原有顺序。
你不能只是单纯的改变节点内部的值,而是需要实际进行节点交换。
输入:head = [1,2,3,4,5], k = 2
输出:[2,1,4,3,5]
> 代码
/**
* 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* reverse(ListNode* head){
if(!head || !head->next) return head;
ListNode* pre = nullptr;
ListNode* cur = head;
ListNode* tmp;
while(cur)
{
tmp = cur->next;
cur->next = pre;
pre = cur;
cur = tmp;
}
return pre;
}
ListNode* reverseKGroup(ListNode* head, int k) {
if(!head || !head->next || k == 1) return head;
ListNode* dumy = new ListNode();
dumy -> next = head;
ListNode* pre = dumy;
ListNode* end = dumy;
while(end->next){
for(int i = 0;i < k && end;i++){
end = end->next;
}
if(!end){
break;
}
ListNode* nex = end->next;
end->next = nullptr;
ListNode* start = pre->next;
pre->next = reverse(start);
start->next = nex;
pre = start;
end = start;
}
return dumy->next;
}
};