# 欢迎大家阅读参考，如有错误或疑问请留言纠正，谢谢

Reverse Nodes in k-Grou

Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.

If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.

You may not alter the values in the nodes, only nodes itself may be changed.

Only constant memory is allowed.

For example,

Given this linked list: 1->2->3->4->5

For k = 2, you should return: 2->1->4->3->5

For k = 3, you should return: 3->2->1->4->5

```class Solution {
//once the link order of the list is changed,
//we must keep the previous pointer(p in the code) updated, if we want to use it agian
public:
void reverse_range(ListNode* prev, ListNode* end, ListNode*& p)
{
ListNode* last = prev->next;
ListNode* cur = last->next;
while(cur != end)
{
last->next = cur->next;
cur->next = prev->next;
prev->next = cur;

cur = last->next;
}
p = last;
}
ListNode *reverseKGroup(ListNode *head, int k)
{
if(k <= 1) return head;
ListNode *dummy = new ListNode(-1);
ListNode* prev = dummy;
ListNode* p = dummy->next;
int cnt = 1;
while(p != NULL)
{
if(cnt%k == 0)
{
reverse_range(prev, p->next, p);//update p is very important
prev = p;
}
p = p->next;
cnt++;
}
return dummy->next;
}
};```
```#include<iostream>

using namespace std;

#define N 5

struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};

class Solution {
//once the link order of the list is changed,
//we must keep the previous pointer(p in the code) updated, if we want to use it agian
public:
void reverse_range(ListNode* prev, ListNode* end, ListNode*& p)
{
ListNode* last = prev->next;
ListNode* cur = last->next;
while(cur != end)
{
last->next = cur->next;
cur->next = prev->next;
prev->next = cur;

cur = last->next;
}
p = last;
}
ListNode *reverseKGroup(ListNode *head, int k)
{
if(k <= 1) return head;
ListNode *dummy = new ListNode(-1);
ListNode* prev = dummy;
ListNode* p = dummy->next;
int cnt = 1;
while(p != NULL)
{
if(cnt%k == 0)
{
reverse_range(prev, p->next, p);//update p is very important
prev = p;
}
p = p->next;
cnt++;
}
return dummy->next;
}
};

ListNode *creatlist()
{
ListNode *head = NULL;
ListNode *p;
for(int i=0; i<N; i++)
{
int a;
cin>>a;
p = (ListNode*) malloc(sizeof(ListNode));
p->val = a;
}
}

int main()
{
ListNode *list = creatlist();
Solution lin;
int a;
cin>>a;
ListNode *outlist = lin.reverseKGroup ( list,a );
for(int i=0; i<N; i++)
{
cout<<outlist->val;
outlist = outlist->next;
}
}```

## python groupby

groupby() 将key函数作用于原循环器的各个元素.根据key函数结果,将拥有相同函数结果的元素分到一个新的循环器.每个新的循环器以函数返回结果为标签. 这就好像一群人的身高作为循环器.我们可以使 用这样一个key函数: 如果身高大于180,返回"tall":如果身高底于160,返回"short";中间的返回"middle".最终,所有身高将分为三个循环器, 即"tall", "short", &qu