ListNode* ReverseList(ListNode* head, ListNode* tail) { ListNode* pre = NULL; ListNode* next = NULL; while (head != tail) { next = head->next; head->next = pre; pre = head; head = next; } return pre; } ListNode* reverseKGroup(ListNode* head, int k) { if (head == NULL || head->next == NULL) { return head; } ListNode* tail = head; for (int i = 0; i < k; i++) { //剩余数量小于k的话,则不需要反转。 if (tail == NULL) { return head; } tail = tail->next; } // 反转前 k 个元素 ListNode* newHead = ReverseList(head, tail); //下一轮的开始的地方就是tail head->next = reverseKGroup(tail, k); return newHead; }
struct ListNode { int val; struct ListNode *next; ListNode(int x):val(x), next(NULL) { } };