题目链接

/**
 * struct ListNode {
 *    int val;
 *    struct ListNode *next;
 * };
 */

class Solution {
public:
    /**
     * 
     * @param head ListNode类 
     * @param k int整型 
     * @return ListNode类
     */
    ListNode* reverseKGroup(ListNode* head, int k) {
        if(head==NULL||head->next ==NULL||k==1)
        {
            return head;
        }
        ListNode *start = new ListNode(0);
        start->next= head;
        int length=0;
        ListNode *pre = start;
        ListNode *cur = head;
        ListNode *temp = NULL;
        while(head!=NULL) //计算链表长度
        {
            length++;
            head=head->next;
        }
        for(int i=0;i<length/k;i++)
        {
            for(int j=1;j<k;j++)
            {
                temp=cur->next;
                cur->next= temp->next;
                temp->next = pre->next;
                pre->next = temp;
            }
            pre = cur;
            cur=cur->next;

        }
        return start->next;
    }

};

图片说明