classSolution{public:ListNode*reverseKGroup(ListNode*head,intk){if(head==nullptr)returnnullptr;ListNode*tail=head;for(inti=0;i<k;++i){if(tail==nullptr)// Less than k nodes, do nothingreturnhead;tail=tail->next;}ListNode*newHead=reverse(head,tail);head->next=reverseKGroup(tail,k);returnnewHead;}private:// Reverses [head, tail)ListNode*reverse(ListNode*head,ListNode*tail){ListNode*prev=nullptr;ListNode*curr=head;while(curr!=tail){ListNode*next=curr->next;curr->next=prev;prev=curr;curr=next;}returnprev;}};
classSolution{publicListNodereverseKGroup(ListNodehead,intk){if(head==null)returnnull;ListNodetail=head;for(inti=0;i<k;++i){if(tail==null)// Less than k nodes, do nothingreturnhead;tail=tail.next;}ListNodenewHead=reverse(head,tail);head.next=reverseKGroup(tail,k);returnnewHead;}// Reverses [head, tail)privateListNodereverse(ListNodehead,ListNodetail){ListNodeprev=null;ListNodecurr=head;while(curr!=tail){ListNodenext=curr.next;curr.next=prev;prev=curr;curr=next;}returnprev;}}
classSolution:defreverseKGroup(self,head:Optional[ListNode],k:int)->Optional[ListNode]:ifnothead:returnNonetail=headfor_inrange(k):ifnottail:# Less than k nodes, do nothingreturnheadtail=tail.nextnewHead=self._reverse(head,tail)head.next=self.reverseKGroup(tail,k)returnnewHead# Reverses [head, tail)def_reverse(self,head:Optional[ListNode],tail:Optional[ListNode])->Optional[ListNode]:prev=Nonecurr=headwhilecurr!=tail:next=curr.nextcurr.next=prevprev=currcurr=nextreturnprev