这题有点繁琐,在更新指针时很容易出错。
ListNode *reverseKGroup(ListNode *head, int k) { if (head == nullptr || head->next == nullptr || k < 2)return head; ListNode dummy(-1); dummy.next = head; for (ListNode *prev = &dummy, *end = head; end; end = prev->next) { for (int i = 1; i < k; i++) end = end->next; if (end == nullptr)break; prev = reverse(prev, prev->next, end); } return dummy.next; } ListNode *reverse(ListNode *prev, ListNode *begin, ListNode *end) { ListNode *end_next = end->next; for (ListNode *p = begin, *cur = p->next, *pnext = cur->next; cur != end_next; p = cur, cur = pnext, pnext =cur? pnext->next:nullptr) { cur->next = p;//注意指针的指向是一个一个的改变的 } begin->next = end_next; prev->next = end; return begin; }
时间: 2024-10-02 19:48:49