class Solution {
public:
ListNode
* reverseKGroup(ListNode
* head
, int k
) {
ListNode
*node
= head
;
for (int i
= 0; i
< k
; i
++) {
if (!node
) return head
;
node
= node
->next
;
}
ListNode
*newNode
= reverse(head
, node
);
head
->next
= reverseKGroup(node
, k
);
return newNode
;
}
ListNode
*reverse(ListNode
*start
, ListNode
*end
) {
ListNode
*pre
= NULL;
while (start
!= end
) {
ListNode
*temp
= start
->next
;
start
->next
= pre
;
pre
= start
;
start
= temp
;
}
return pre
;
}
};
转载请注明原文地址:https://tech.qufami.com/read-641.html