My C++ recursion solution


  • 0
    W
    /**
     * 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) {
            int i,j;
            ListNode *check,*rear,*temp,*p;
            check = head;
            for(i=0;i<k;i++){
                if(check==NULL)
                    return head;
                check = check->next;
            }
            temp = head;
            for(i=0;i<k-1;i++)
                temp = temp->next;
            rear = temp;
            for(i=k-1;i>0;i--){
                p = head;
                for(j=0;j<i-1;j++)
                    p = p->next;
                temp->next = p;
                temp = p;
            }
            head->next = reverseKGroup(check,k);
            return rear;
        }
    };
    

Log in to reply
 

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