/**
 * struct ListNode {
 *	int val;
 *	struct ListNode *next;
 *	ListNode(int x) : val(x), next(nullptr) {}
 * };
 */
class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param head ListNode类 
     * @param k int整型 
     * @return ListNode类
     */
    ListNode* reverseKGroup(ListNode* head, int k) {
        // write code here
        //找到每次翻转尾部
        ListNode *tail = head;
        //遍历k次到段尾部
        for(int i = 0; i < k; i++){
            //段内长度不足k直接返回
            if(tail == NULL){
                return head;
            }
            tail = tail->next;
        }
        //翻转的前序节点和当前结点
        ListNode *pre = NULL;
        ListNode *cur = head;
        
         //在到达当前段 段尾结点前
        while(cur != tail){
            ListNode *temp = cur->next;
            cur->next = pre;
            //非next先动前面的
            pre = cur;
            cur = temp;
            
        }
        //递归——当前尾结点指向 下一段tail 要反转的链表段
        head->next = reverseKGroup(tail,k);
        //返回值: 每一级要返回的就是翻转后的这一分组的头
        return pre;
    }
};