题解 | #链表中的节点每k个一组翻转#
链表中的节点每k个一组翻转
http://www.nowcoder.com/practice/b49c3dc907814e9bbfa8437c251b028e
先进行链表的长度的遍历,然后计算总共的逆序轮数,最后余下的直接接在新的链表的末尾即可。
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
class Solution {
public:
/**
*
* @param head ListNode类
* @param k int整型
* @return ListNode类
*/
ListNode* reverseKGroup(ListNode* head, int k) {
// write code here
ListNode* newhead = (ListNode*)malloc(sizeof(ListNode));
newhead->next = NULL;
newhead->val = -1;
ListNode *curhead = newhead,*pre = NULL,*temp,*curnext;
pre = head;
int cnt = 0;
while(pre){
cnt++;
pre = pre->next;
}
//判断次数与剩下节点数
int circle = cnt / k;
int mod = cnt - circle * k;
pre = NULL;
while(circle--){
for(int i = 1;i <= k;++i){
temp = curhead->next;
curnext = head->next;
curhead->next = head;
if(pre == NULL)
pre = head;
head->next = temp;
head = curnext;
}
curhead = pre;
pre = NULL;
}
if(mod)
curhead->next = head;
return newhead->next;
}
};