> For the complete documentation index, see [llms.txt](https://jenhsuan.gitbook.io/algorithm/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://jenhsuan.gitbook.io/algorithm/leetcode/25.-reverse-nodes-in-k-group.md).

# 25. Reverse Nodes in k-Group

## 1.問題

* 給予一個linked list, 回傳k組排序的結果

![](/files/-LNjojiO7RSVDuEb3dPK)

## 2.想法

* 提問
* function header, parameter
* test inpu
* 說明想法
  * 遞迴作法:
    * base case: 不到k個node的話, return head
    * 將next = curr->next
    * curr-> next 接到前一組k group排序的結果
    * 排序當前的k group
* 測試計算複雜度: O(n)

## **3.程式碼**

```
/**
 * 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) {
        //base case: 如果數目不到k, 回傳head
        ListNode* next = head; 
        int i = 0;
        while (next && i < k) {
            next = next->next;
            i++;
        } 
        
        if (i < k) {
            return head;
        }
        
        //pre為上一組k group的頭
        ListNode* pre = reverseKGroup(next, k);
        
        //reverse當前的k group 
        ListNode* curr = head;
        for (int i = 0; i < k; i++) {
            next = curr->next;
            curr->next = pre;
            pre = curr;
            curr = next;
        }
        
        return pre;
    }
};
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## 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, and the optional `goal` query parameter:

```
GET https://jenhsuan.gitbook.io/algorithm/leetcode/25.-reverse-nodes-in-k-group.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

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.
