---
# System prepended metadata

title: Leetcode . 題目

---

# Leetcode 25. Reverse Nodes in k-Group

## 題解

先算出鍊表總長度，計算需要分多少次，依序切分併入答案即可，最後的尾部記得要加上

### 方法

```python!
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def reverseKGroup(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
        # Time complexity: O(n)
        # Space complexity: O(1) , 併入答案計算 O(n)
        
        result = ListNode()
        rp = result
        p = head

        def list_length(head: ListNode) -> int:
            count = 0
            while head:
                count += 1
                head = head.next
            return count
        
        length = list_length(head)
        secs = length // k
        left = length % k
        
        for i in range(secs):
            nodes = None
            for j in range(k):
                next_p = p.next
                p.next = nodes
                nodes = p
                p = next_p
            nodes_p = nodes
            for j in range(k-1):
                nodes_p = nodes_p.next
            rp.next = nodes
            rp = nodes_p
        rp.next = p
        return result.next
```
