又是上一题的加强版,还是用递归解决,虽然慢,但是好写啊~主要思想,先把前k个reverse,再递归计算剩下的链表
ListNode* reverseKGroup(ListNode* head, int k) {
int length = 0;
ListNode* front = head, *back, *tail;
while(front != NULL){length++; front = front->next;}
if(length < k)return head;
ListNode pre(-1);
pre.next = head;
front = pre.next;
back = front->next;
tail = front;
for(int i = 1; i < k; i++){
cout << front->val << " " << back->val << endl;
tail->next = back->next;
back->next = front;
pre.next = back;
front = pre.next;
back = tail->next;
}
tail->next = reverseKGroup(tail->next, k);
return pre.next;
}