My Recursive Solution C++ 32ms


  • 0
    T
    class Solution {
        public:
            ListNode *reverseKGroup(ListNode *head, int k) {
                if(head==NULL||head->next==NULL||k<=1)return head;
                
                ListNode *p=head;
        		int Lenght=0;
        		while(p)
        		{
        			Lenght++;
        			p=p->next;
        		}
        		return RecursiveKGroup(head,k,Lenght);
            }
        	ListNode *RecursiveKGroup(ListNode *head, int k,int lenght)
        	{
        		if(lenght<k) return head;
        		ListNode *Tail=head;
        		ListNode *Head=head;
        		//Tail->next=NULL;
        		head=head->next;
        		ListNode *p=head;
        		p=p->next;
        		int t_k=k-1;
        		while(t_k--)
        		{
        			head->next=Head;
        			Head=head;
        			head=p;
        			if(p)
        			p=p->next;
        		}
        		Tail->next=RecursiveKGroup(head,k,lenght-k);
        		return Head;
        	}
        };

Log in to reply
 

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