LL - k Reverse it show wrong in some testcase

#include
using namespace std;
class Node{
public:
int data;
Nodenext;
Node(int d)
{
data=d;
next=NULL;
}
};
void insert(Node
&head,int data)
{

if(head==NULL)
{
	head=new Node(data);
    return;
	
}
Node*temp1=head;
while(temp1->next!=NULL)
{
	temp1=temp1->next;
}
temp1->next=new Node(data);
return;

}
void print(Nodehead)
{
while(head!=NULL)
{
cout<data<<" ";
head=head->next;
}
}
void linkedlist(Node
&head,int n)
{
int data;
while(n–)
{
cin>>data;
insert(head,data);
}
return;
}
void reverse(Nodehead,int t)
{
t=3;
Node
temp=head;
Node*temp1=head;
if(temp==NULL||temp->next==NULL)
{
return;
}
int a;

while(t>1)
{
temp=temp->next;
t–;
}
a=temp->data;
temp->data=temp1->data;
temp1->data=a;
reverse(temp->next,t);
}
int main() {
int n,t;
cin>>n;
cin>>t;
Node*head=NULL;
linkedlist(head,n);
reverse(head,t);
print(head);
return 0;
}

Hello @17manishms,

  1. Following statement was generalizing your code for k=3
    t=3;
    Solution:
    //Create a temporary variable use it instead of t
    int t1=t;
    //Use t1
    while(t1>1)
    {
    temp=temp->next;
    t1–;
    }

  2. The logic you have used would work only for k=1,2 and 3.
    It will cause wrong output for k>3
    Example:
    8 4
    9 4 1 7 8 3 2 6
    Problem:
    You are swapping leftmost with right most which incorrect.

Suggestion:
Watch the video: K Reverse Hint of your course.

You can refer to the following for better understanding:

Hope, this would help.
Give a like if you are satisfied.

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.