25. Reverse Nodes in k-Group

https://leetcode.com/problems/reverse-nodes-in-k-group/description/

对给定的linked list每K个做一次反转。把K个当成一组做翻转,然后把翻转后的新头,断口,和剩下的返回。对剩下的继续此过程,返回后把上个断口和当前次新头拼上。让head记录第一次返回的新头。

/*
 * @lc app=leetcode id=25 lang=cpp
 *
 * [25] Reverse Nodes in k-Group
 */
/**
 * 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)
    {
        const auto reverseK = [](ListNode *head, int k) {
            ListNode *cur = head;
            for (int i = 0; i < k - 1; ++i)
            {
                if (cur == nullptr)
                    return vector<ListNode *>({head});
                cur = cur->next;
            }
            if (cur == nullptr)
                return vector<ListNode *>({head});
            const auto rest = cur->next;
            cur->next = nullptr;
            cur = head;
            ListNode *pre = nullptr;
            while (cur != nullptr)
            {
                const auto next = cur->next;
                cur->next = pre;
                pre = cur;
                cur = next;
            }
            head->next = rest;
            // new head, new tail, rest
            vector<ListNode *> res({pre, head, rest});
            return res;
        };
        bool end = false;
        ListNode *cur = head, *ptail = nullptr;
        head = nullptr;
        while (cur != nullptr)
        {
            auto r = reverseK(cur, k);
            if (head == nullptr)
                head = r[0];
            if (r.size() == 1)
                break;
            if (ptail != nullptr)
                ptail->next = r[0];
            cur = r[2];
            ptail = r[1];
        }
        return head;
    }
};

Last updated