# [leetcode题解]25.Reverse Nodes in k-Group(链表每k个元素逆置)

python代码：

```# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
def reverseKGroup(self, head, k):
"""
:type head: ListNode
:type k: int
:rtype: ListNode
:author: 凌风技术站-iaccepted
"""
pre = ListNode(-1)
tail = pre

q = head
while q is not None:
#向后查找k个节点
n = k
p = q
while p is not None and n > 0:
p = p.next
n -= 1

#如果在查找k个节点的过程中遇到None，则说明
#后面的节点不够k个节点则直接跳出即可
if n > 0:
tail.next = q
break

#将这K个节点以头插法插入
end = q
while q != p:
t = q.next
q.next = tail.next
tail.next = q
q = t
tail = end
return pre.next
```

c++代码：

```class Solution {
public:
ListNode* reverseKGroup(ListNode* head, int k)
{
ListNode *pre = new ListNode(-1), *tail = pre;

ListNode *p = head;
while(p != NULL)
{
ListNode *q = p;
int cnt = 0;
for (int i = 0; i < k && q != NULL; ++i)
{
q = q->next;
++cnt;
}

if (cnt < k)
{
tail->next = p;
break;
}
ListNode *end = p;
while(p != q)
{
ListNode *t = p->next;
p->next = tail->next;
tail->next = p;
p = t;
}
tail = end;
}
return pre->next;
}
};```