code for reverse nodes in k groups

Example 1:
Input: head = [1,2,3,4,5], k = 2
Output: [2,1,4,3,5]

Example 2:
Input: head = [1,2,3,4,5], k = 3
Output: [3,2,1,4,5]
pull/895/head
Joyeta Saha 2022-10-02 23:07:46 +05:30 committed by GitHub
parent 62907b69ec
commit 94d5eee415
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 33 additions and 0 deletions

View File

@ -0,0 +1,33 @@
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
int length(ListNode *head){
int len=0;
while(head){
len++;
head=head->next;
}
return len;
}
ListNode* reverseKGroup(ListNode* head, int k) {
if(length(head)<k) return head;
ListNode *prev=NULL,*curr=head;
for(int i=0;i<k;i++){
ListNode *n=curr->next;
curr->next=prev;
prev=curr;
curr=n;
}
head->next=reverseKGroup(curr,k);
return prev;
}
};