LeetCode 25. k個一組翻轉連結串列

TomorrowWu發表於2019-02-16

題目描述

這裡寫圖片描述

解題思路

分別求解併合並

分成若干個K個一段的,然後將每個進行翻轉,最後將他們連線起來即可。

程式碼實現

struct ListNode
{
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};
class Solution
{
public:
    ListNode* rev(ListNode* head)
    {
        if(head == NULL || head->next == NULL) return head;
        ListNode* p = head, *q = p->next, *r;
        while(q != NULL)
        {
            r = q->next;
            q->next = p;
            p = q;
            q = r;
        }
        return p;
    }

    ListNode* reverseKGroup(ListNode* head, int k)
    {
        ListNode* fast = head, *re = head,  *pre = NULL;
        int length = 0;
        while(length++ != k)
        {
            if(fast == NULL) return head;
            pre = fast;
            fast = fast->next;
        }
        pre->next = NULL;
        re = rev(head);
        head->next = reverseKGroup(fast, k);
        return re;
    }
};

相關文章