Reverse linked list by first K elements

Coding Blocks IDE

Coding Blocks IDE
Coding Blocks Online IDE | Run and check your code

This is my code to reverse linked list by K nodes means if my LL is
push(head,4);
push(head,5);
push(head,8);
push(head,9);
push(head,3);
push(head,1);
push(head,2);
then reverse by K if K=3 then its giving 2 9 8 5 4 when it should give 3 1 2 9 8 5 4
Its not working . pls tell where its wrong

where is the Code???
:joy:

#include
using namespace std;
class LL{
public:
int data;
LL *next;
LL(int d)
{
data=d;
next=NULL;
}
};
void push(LL &head,int data)
{
LL
temp = new LL(data);
temp->next = head;
head = temp;
}
void reversebyK(LL *&head,int K)
{
int jump=1;
LL *prev=NULL;
LL *current=head;
while(jump<=K-1)
{
prev=current;
current=current->next;
jump++;
}
head->next=current->next;
current->next=prev;
prev->next=head;
head=current;
}
void print(LL *head)
{
while(head!=NULL)
{
cout<data<<"->";
head=head->next;
}
cout<<endl;
}
int main() {
LL *head=NULL;
push(head,4);
push(head,5);
push(head,8);
push(head,9);
push(head,3);
push(head,1);
push(head,2);
cout<<“before reversing”<<endl;
print(head);
reversebyK(head,3);
cout<<“after reversing”<<endl;
print(head);
}

Here is the code

instead of pasting your code here you can paste it at


and send the link generated

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.