A simple solution in c++ in 3 steps


  • 0

    I solve this problem in the 2 steps.
    1.calculate the reversal times .
    2.connect the last part's tail to the current part's head.
    3.connect the left nodes (if have left).

    ListNode* reverseKGroup(ListNode* head, int k)
    {
        int len =  listLen(head), times = len / k;
        if (head == NULL || times <= 0) {
            return head;
        }
        ListNode *p1, *p2, *p3, *ansHead = head, *tail = head;
        while (times --) {
            p1 = head;
            p2 = p1 -> next;
            p1 -> next = NULL;
            int cnt = 0;
            while (p2 && cnt ++ < k - 1) {
                p3 = p2 -> next;
                p2 -> next = p1;
                p1 = p2;
                p2 = p3;
            }
            if(times == len / k - 1){
                ansHead = p1;
            }
            else{
                tail -> next = p1;
                tail = head;
            }
            head = p2;
    
        }
        while (head) {
            tail -> next = head;
            tail = tail -> next;
            head = head -> next;
        }
        return ansHead;
    }

Log in to reply
 

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