题解 | #链表中的节点每k个一组翻转#(头插法&边插入边走)
链表中的节点每k个一组翻转
http://www.nowcoder.com/practice/b49c3dc907814e9bbfa8437c251b028e
/** 想想大牛 怎么做
反转链表, 头插法 需要一个头指针
建立一个头指针
k-1次头插,更新 头指针
*/
class Solution {
public:
ListNode* reverseKGroup(ListNode* head, int k) {
if(head == NULL||k==1) return head;
ListNode *res = new ListNode(0);
res->next = head; // 建立一个头指针
int len = 0;
ListNode *pre = res, *cur = head, *tmp;
while(head != NULL){
len++;
head = head->next;
}
for(int i = 0; i < len/k; i++){
for(int j = 1; j < k; j++){ // 头插法k-1次
tmp = cur->next; // tmp 代表摘下的节点
cur->next = tmp->next; // 将节点摘下
tmp->next = pre->next; // 将摘下的节点连接到
pre->next = tmp;
}
pre = cur; // 更改头指针 为上一个翻转的尾结点
cur = cur->next; // 指向下一组的第一个结点。
}
return res->next;
}
};