C++ 24 ms code, judge whether there is K node first


  • 0
    Z
    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution {
        bool check(ListNode* head, int k)
        {
            if(head==NULL)return false;
            int i = 1;
            while(++i<=k)
            {
                head = head->next;
                if(!head)
                return false;
            }
            return true;
        }
    public:
        ListNode* reverseKGroup(ListNode* head, int k) {
            if(head == NULL) return NULL;
            ListNode* p = NULL,*pa= NULL,*q= NULL,*m= NULL,*lastpa= NULL;
            p = head,pa = head;
            while(1)
            {
                if(!(check(pa,k)))
                break;
                int i = 1;
                q = pa->next;
                p = pa;
                while(++i<=k)
                {// reverse a section
                    m = q->next;
                    q->next = p;
                    p = q;
                    q = m;
                }
                if(pa == head)
                {// reset HEAD node
                    head = p;
                }
                if(lastpa) // last pa means the final node of previous section
                lastpa->next = p; //conect two sections
                lastpa = pa; //reset para
                pa = q;
            }
            if(lastpa)
                lastpa->next = q;
            return head;
        }
    };

Log in to reply
 

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