// 找到 left处的节点,即为cur, pre一直是left前不用换的那个节点, nxt是cur后的节点, cur和nxt会不停变换 for(int i = 1; i < left; i++){ pre = cur; cur = cur -> next; nxt = cur -> next; }
// 每次把 nxt 头插进去 for(int i = left; i < right; i ++){ cur -> next = nxt -> next; nxt -> next = pre -> next; pre -> next = nxt; nxt = cur -> next; } return dummyHead -> next; } };
while(head){ len ++; head = head -> next; } head = dummyHead -> next;
for(int i = 0; i< len / k; i ++){ pair<ListNode*,ListNode*> p = reverse(curr, k); prev -> next = p.first; curr -> next = p.second; prev = curr; curr = curr -> next; }
return dummyHead -> next; }
pair<ListNode*,ListNode*> reverse(ListNode* head, int k){ //返回翻转后的 <新头节点,原来尾部下一个节点> if(k == 1) return {head, head -> next}; pair<ListNode*,ListNode*> res = reverse(head -> next, --k); head -> next -> next = head; head -> next = nullptr; return res; } };