My clear cpp code


  • 0
    C
    class Solution {
    public:
        ListNode* reverse(ListNode* head, ListNode* tail)
        {
            ListNode* newHead = NULL;
            
            while(head != tail)
            {
                ListNode* tmp = head->next;
                head->next = newHead;
                
                newHead = head;
                head = tmp;
            }
            
            return newHead;
        }
        
        ListNode* findNextGrp(ListNode* head, int k, bool& isKGrp)
        {
            for(int i=0; i<k; i++)
                if(head) head = head->next;
                else     return NULL;
                
            isKGrp = true;
            return head;
        }
        
        ListNode* reverseKGroup(ListNode* head, int k) 
        {
            ListNode fakeHead(0);
            ListNode* ptr = &fakeHead;
            
            while(head)
            {
                bool isKGrp = false;
                ListNode* nextGrp = findNextGrp(head, k, isKGrp);
                
                if(isKGrp) ptr->next = reverse(head, nextGrp);
                else
                {
                    ptr->next = head;
                    break;
                }
                
                ptr = head;
                head = nextGrp;
            }
            
            return fakeHead.next;
        }
    };

Log in to reply
 

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