8 ms c version code for K-group


  • 0
    D
    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     struct ListNode *next;
     * };
     */
    struct ListNode* reverse_with_lengtn(struct ListNode* pre,int len)
    {
        if(len <= 1)
            return pre;
        int i = 1;
        struct ListNode* head = pre;
        struct ListNode* next = NULL;
        struct ListNode* cur = pre->next;
        for(; i < len;++i)
        {
            next = cur->next;
            cur->next = pre;
            pre = cur;
            cur = next;
        }
        head->next = next;
        return pre;
    }
    
    int getNodeCount(struct ListNode* head)
    {
        int len = 0;
        while(head)
        {
            ++len;
            head = head->next;
        }
        return len;
    }
    
    struct ListNode* reverseKGroup(struct ListNode* head, int k) {
        if(k == 0 || k == 1)
            return head;
    
        struct ListNode* cur = head;
        struct ListNode* section_end = NULL;
        struct ListNode* res = NULL;
        int section = getNodeCount(head) / k;
        if(section == 0)
            return head;
        for(int i = 0; i < section;++i)
        {
            if(i == 0)
            {
                res = reverse_with_lengtn(cur,k);
                section_end = cur;
                cur = cur->next;
            }
            else
            {
                section_end->next = reverse_with_lengtn(cur,k);
                section_end = cur;
                cur = cur->next;
            }
        }
        return res;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.