[LeetCode] Reverse Nodes in k-Group

Given a linked list, reverse the nodes of a linked list k at a time and return its modified list. If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is. You may not alter the values in the nodes, only nodes itself may be changed. Only constant memory is allowed. For example, given this linked list: 1->2->3->4->5
       For k = 2, you should return: 2->1->4->3->5

       For k = 3, you should return: 3->2->1->4->5

相关问题:Swap Nodes in Pairs

题目的要求是,当链表剩余长度不足k,不进行翻转。下面给出一个算法,该算法会将剩余链表翻转,不论剩余链表的长度是否小于k。

    ListNode *reverseKGroup(ListNode *head, int k) {
        ListNode* current = head;
        ListNode* next = NULL;
        ListNode* prev = NULL;
        int count = 0;   
         
        /*reverse first k nodes of the linked list */
        while (current != NULL && count < k)
        {
           next  = current->next;
           current->next = prev;
           prev = current;
           current = next;
           count++;
        }
         
        /* next is now a pointer to (k+1)th node 
           Recursively call for the list starting from current.
           And make rest of the list as next of first node */
        if(next !=  NULL)
        {  
            head->next = reverseKGroup(next, k); 
            
        }
     
        /* prev is new head of the input list */
        return prev;
    }   

下面的代码,不会反转剩余链表。与上面代码唯一不同之处在于,多了一个 if(count<k) 的判断。

    ListNode *reverseKGroup(ListNode *head, int k) {
        ListNode* current = head;
        ListNode* next = NULL;
        ListNode* prev = NULL;
        int count = 0;   
         
        /*reverse first k nodes of the linked list */
        while (current != NULL && count < k)
        {
           next  = current->next;
           current->next = prev;
           prev = current;
           current = next;
           count++;
        }
        
        // The following code block will reverse the tail sub-list whose size is less than k
        if(count<k)
        {
            current = prev;
            next = NULL;
            prev = NULL;
            while (current != NULL)
            {
               next  = current->next;
               current->next = prev;
               prev = current;
               current = next;
            }
            
            return head;
        }
         
        /* next is now a pointer to (k+1)th node 
           Recursively call for the list starting from current.
           And make rest of the list as next of first node */
        if(next !=  NULL)
        {
            head->next = reverseKGroup(next, k);
        }
     
        /* prev is new head of the input list */
        return prev;
    }     
   



你可能感兴趣的:(LeetCode)