LeetCode25. K 个一组翻转链表

    科技2024-06-06  80

    //25. K 个一组翻转链表 class Solution { public: ListNode* reverseKGroup(ListNode* head, int k) { ListNode* ans = new ListNode(-1); ans->next = NULL; auto end = ans; auto p = head; int cnt = 0; while (p != NULL) { auto t = p; p = p->next; t->next = end->next; end->next = t; cnt++; if (cnt == k) { while (cnt) { end = end->next; cnt--; } } } if (cnt) { p = end->next; end->next = NULL; while (p != NULL) { auto t = p; p = p->next; t->next = end->next; end->next = t; } } return ans->next; } };
    Processed: 0.014, SQL: 8