> 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組排序的結果

![](https://901207480-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LGKoChvN9am4__HCIRK%2F-LNjo6iBT4RLXFn1EGeL%2F-LNjojiO7RSVDuEb3dPK%2F%E8%9E%A2%E5%B9%95%E5%BF%AB%E7%85%A7%202018-10-01%20%E4%B8%8B%E5%8D%889.30.27.png?alt=media\&token=d26d6c83-35ff-46ad-bc4f-45da73adb97f)

## 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;
    }
};
```
