Leetcode|25. K 个一组翻转链表(递归反转链表)

2021-09-18 17:26:58 浏览数 (1)

1 递归反转链表

代码语言:javascript复制
class Solution {
public:
    // 在[first, end)区间内反转链表
    ListNode* reverseBetween(ListNode* first, ListNode* end) {
        ListNode* pre = nullptr;
        ListNode* cur = first;
        while (cur != end) {
            auto next = cur->next;
            cur->next = pre;
            pre = cur;
            cur = next;
        }
        return pre;
    }

    ListNode* reverseKGroup(ListNode* head, int k) {
        if (!head) return nullptr;
        auto first = head;
        auto end = head;
        for (int i = 0; i < k; i  ) {
            if (!end) return head;
            end = end->next;
        }
        auto newHead = reverseBetween(first, end);
        // 之前的first到现在就是end - 1
        first->next = reverseKGroup(end, k);
        return newHead;
    }
};

0 人点赞