题解
将单链表的每K个节点之间逆序
http://www.nowcoder.com/questionTerminal/66285653d28b4ed6a15613477670e936
vector<list_node*> reverseN(list_node * head1, int K) { list_node* pre = nullptr; list_node* next = nullptr; vector<list_node*> res; res.push_back(head1); while(K--) { next = head1->next; head1->next = pre; pre = head1; head1 = next; } res.push_back(pre); res.push_back(head1); return res; } list_node * reverse_knode(list_node * head1, int K) { //////在下面完成代码 list_node* cur = head1; int n = 0; while(cur != nullptr) { n++; cur = cur->next; } n /= K; //逆序n次 vector<list_node*> p; //p[0]:逆序后的尾节点 p[1]:逆序后的头节点 p[2]:逆序后的下一个节点 vector<vector<list_node*>> list; //每次逆序的P放入list中 while(n--) { p = reverseN(head1, K); //依次逆序K个节点 list.push_back(p); //存入P head1 = p[2]; //下一个节点给head1 } //将list中的节点头尾相连 for(int i=0; i<(int)list.size()-1; i++) { list[i][0]->next = list[i+1][1]; } list[(int)list.size()-1][0]->next = head1; //接入剩下的节点 return list[0][1]; }