25-K个一组翻转链表

tech2022-07-13  169

/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* reverseKGroup(ListNode* head, int k) { ListNode *node = head; for (int i = 0; i < k; i++) { if (!node) return head; node = node->next; } ListNode *newNode = reverse(head, node); head->next = reverseKGroup(node, k); return newNode; } // 链表翻转 ListNode *reverse(ListNode *start, ListNode *end) { ListNode *pre = NULL; while (start != end) { ListNode *temp = start->next; start->next = pre; pre = start; start = temp; } return pre; } };
最新回复(0)