Difficulty: Hard
这道题给 Hard 其实没必要,简单而言就是一个大的链表翻转套一个小的链表翻转,但在处理的时候要小心节点操作顺序。
这段代码还可以处理得更简洁一点,比如加一个过头元,通过计数来判断是不是一组,等等
class Solution {
public:
ListNode *reverseKGroup(ListNode *head, int k) {
if (k == 1)
return head;
ListNode *p = head;
ListNode *newhead = head;
ListNode *lastend = NULL;
while (p) {
ListNode *begin = p;
for (int i = 0; i < k - 1; i++) {
p = p->next;
if (!p)
return newhead;
}
ListNode *end = p;
if (newhead == head)
newhead = end;
if (lastend)
lastend->next = end;
p = p->next;
rev(begin, k);
begin->next = p;
lastend = begin;
}
return newhead;
}
ListNode *rev(ListNode *begin, int k) {
ListNode *p = begin;
ListNode *pp = p->next;
ListNode *ppp;
for (int i = 1; i <= k - 1; i++) {
ppp = pp->next;
pp->next = p;
p = pp;
pp = ppp;
}
return pp;
}
};