My C++ Codes


  • 0
    P
    /**
     * 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) {
            if(!head || !head->next || k == 1)
                return head;
                
            ListNode dummy(-1);
            dummy.next = head;
            
            bool isTail = true;
            ListNode *pre = &dummy, *slow = &dummy, *fast = &dummy, *tail = &dummy;
            slow = pre->next;
            while(tail && slow){
                for(int i = 0; i < k; i++)
                    if(tail->next)
                        tail = tail->next;
                    else{
                        isTail = false;
                        break;
                    }
                
                if(!isTail)
                    break;
                
                while(fast != tail){
                    fast = slow->next;
                    
                    slow->next = fast->next;
                    fast->next = pre->next;
                    pre->next = fast;
                }
                pre = slow;
                tail = slow;
                slow = pre->next;
                    
            }
            
            return dummy.next;
        }
    };
    

Log in to reply
 

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