# 25. Reverse Nodes in k-Group

对给定的linked list每K个做一次反转。把K个当成一组做翻转，然后把翻转后的新头，断口，和剩下的返回。对剩下的继续此过程，返回后把上个断口和当前次新头拼上。让head记录第一次返回的新头。

```cpp
/*
 * @lc app=leetcode id=25 lang=cpp
 *
 * [25] Reverse Nodes in k-Group
 */
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution
{
public:
    ListNode *reverseKGroup(ListNode *head, int k)
    {
        const auto reverseK = [](ListNode *head, int k) {
            ListNode *cur = head;
            for (int i = 0; i < k - 1; ++i)
            {
                if (cur == nullptr)
                    return vector<ListNode *>({head});
                cur = cur->next;
            }
            if (cur == nullptr)
                return vector<ListNode *>({head});
            const auto rest = cur->next;
            cur->next = nullptr;
            cur = head;
            ListNode *pre = nullptr;
            while (cur != nullptr)
            {
                const auto next = cur->next;
                cur->next = pre;
                pre = cur;
                cur = next;
            }
            head->next = rest;
            // new head, new tail, rest
            vector<ListNode *> res({pre, head, rest});
            return res;
        };
        bool end = false;
        ListNode *cur = head, *ptail = nullptr;
        head = nullptr;
        while (cur != nullptr)
        {
            auto r = reverseK(cur, k);
            if (head == nullptr)
                head = r[0];
            if (r.size() == 1)
                break;
            if (ptail != nullptr)
                ptail->next = r[0];
            cur = r[2];
            ptail = r[1];
        }
        return head;
    }
};

```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://hao-fu-1.gitbook.io/oj/linked_list/reverse-list/25.-reverse-nodes-in-k-group.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
