点击打开链接
struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; class Solution { public: ListNode *reverseKGroup(ListNode *head, int k) { ListNode *dummy = new ListNode(-1), *pre = dummy, *cur = pre; dummy->next = head; int num = 0; while(cur = cur->next) ++num; while(num>=k){ cur = pre->next; //在一段链表中间一段子链表翻转的经典模版 for(int i=1; i<k; i++){//pre->a->b->c 先pre->b->a->c 再pre->c->b->a 把元素依次往前插 ListNode* t = cur->next; cur->next = t->next; t->next = pre->next; pre->next = t;; } pre = cur;//刚开始最前面的cur也就是下一阶段的pre, 然后pre->next就是下一个的cur了 num -= k; } return dummy->next; } };