先求出链表长度,得到需要翻转的次数(len/k)
调用翻转函数,进行翻转;
class Solution { public: /** * * @param head ListNode类 * @param k int整型 * @return ListNode类 */ ListNode* revser(ListNode* head, int n) { ListNode* newhead = new ListNode(-1); ListNode* flag = head; while (head&&n > 0) { ListNode* temp = head->next; head->next = newhead->next; newhead->next = head; head = temp; n--; } flag->next = head; return newhead->next; } ListNode* reverseKGroup(ListNode* head, int k) { // write code here ListNode* newhead = new ListNode(-1); newhead->next = head; ListNode* first = head; int len = 0; while (first) { first = first->next; len++; } first = newhead; for (int i = 0; i < len / k; i++) { ListNode* pre = first->next; first->next = revser(first->next, k); first = pre; } return newhead->next; } };