https://www.nowcoder.com/practice/b49c3dc907814e9bbfa8437c251b028e?tpId=295&tqId=722&sourceUrl=%2Fexam%2Foj%3FquestionJobId%3D10%26subTabName%3Donline_coding_page

按照题目要求按k个一组分块,然后再将每个块内的链表翻转即可。可以从后往前遍历每个块反转,也可以从前往后递归地反转。

public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param head ListNode类 
     * @param k int整型 
     * @return ListNode类
     */
    ListNode* reverseKGroup(ListNode* head, int k) {
        // write code here
        if(head == nullptr)return head;
        ListNode d(0);
        d.next = head;
        for(int i = 1; i < k; i++) {
            head = head->next;
            if(head == nullptr) return d.next;
        }
        head = &d;
        ListNode* tmp = new ListNode(0), *cur = d.next;
        for(int i = 1; i < k; i++) {
            tmp = cur->next;
            cur->next = tmp->next;
            tmp->next = d.next;
            d.next = tmp;
        }
        cur->next = reverseKGroup(cur->next, k);
        return d.next;
    }
};