Can you explain how to do this;
we will reverse k elements in the linkedlist
then ask recursion to the rest
can reverse k element after recursive call or before recursive call or can we do both ways?
Reverse linkedlist in k groups
questions–>
code–>
/**
* 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:
ListNode* reverseKGroup(ListNode* head, int k) {
if(head==NULL or head->next==NULL){
return head;
}
ListNode* p=NULL;
ListNode* n=NULL;
ListNode* c=head;
int count=0;
while(c!=NULL and count<k){
n=c->next;
c->next=p;
p=c;
c=n;
count++;
}
head->next=reverseKGroup(n,k);
return p;
}
};
my code is not working when the elements left are less than k ,then according to leetcode we should not reverse them;
okay i got it
/**
* 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:
ListNode* reverseKGroup(ListNode* head, int k) {
if(head==NULL or head->next==NULL){
return head;
}
ListNode* p=NULL;
ListNode* n=NULL;
ListNode* c=head;
int count=0;
ListNode* temp=head;
while(temp!=NULL){
count++;
temp=temp->next;
}
if(count<k){
return head;
}
count=0;
while(c!=NULL and count<k){
n=c->next;
c->next=p;
p=c;
c=n;
count++;
}
head->next=reverseKGroup(n,k);
return p;
}
};
but can explain first doubt?
Hello @sheikhhaji18 you have doubt in reversing linked list in the groups of k?
if you have doubt in that only:
if you have any doubt still you can ask here:
Happy Learning!!
I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.
On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.