代码
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) : val(x), next(nullptr) {}
* };
*/
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param head ListNode类
* @param k int整型
* @return ListNode类
*/
ListNode* reverseKGroup(ListNode* head, int k) {
auto tail = head;
//判断k节车厢是否满载
for(int i = 0;i < k;i++){
if(!tail) return head;
tail = tail->next;
}
//反转该k节车厢
ListNode* res = reverse(head, tail);
//继续反转后面的车厢 并且连接(注意此时head为该节车厢的尾部)
head->next = reverseKGroup(tail, k);
return res;
}
ListNode* reverse(ListNode* cur,ListNode* tail){
auto pre = tail;
while(cur != tail){
auto post = cur->next;
cur->next = pre;
pre = cur;
cur = post;
}
return pre;
}
};