Linked -ist k append

logic :
traverse (n-k-1) nodes
then put the (n-k-1)th node’s -> next = null
reinitialise (n-k)th node as head
then traverse the list till the earlier tail and put tail -> next = older head.
and return the new head at last.

and return the old head for k>n case.
doubt: one first two test cases passed
#include<bits/stdc++.h>
using namespace std;
class node{
public:
int data;
node* next;

//Constructor
node(int d){
    data = d;
    next =NULL;
}

};

void insertAtTail(node*&head,int data){

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

}

void print(nodehead){
//node
temp = head;

while(head!=NULL){
    cout<<head->data<<" ";
    head = head->next;
}
cout<<endl;

}
void insertAtHead(node*&head,int data){
noden = new node(data);
n->next = head;
head = n;
}
int length(node
head){

int len=0;
while(head!=NULL){
    head = head->next;
    len += 1;
}
return len;

}

void insertInMiddle(node*&head,int data,int p){

if(head==NULL||p==0){
    insertAtHead(head,data);
}   
else if(p>length(head)){
    insertAtTail(head,data);
}
else{
    //Insert in the middle 
    //Take p-1 jumps
    int jump=1;
    node*temp = head;
    while(jump<=p-1){
        temp = temp->next;
        jump += 1;
    }
    
    node*n = new node(data);
    n->next = temp->next;
    temp->next = n;
    
}

}
node * kappend(node *&head,int l,int k){
if(l>0){
node *temp1;
node *temp2;
int i=0;
temp1=head;
while(temp1!=NULL&&i<l-1){
temp1=temp1->next;
i++;
}

temp2=temp1->next;
temp1->next=NULL;

node *newhead=temp2;
node*head2=temp2;
while(head2->next!=NULL&&head2!=NULL){
    head2=head2->next;
}
if(head2!=NULL){
head2->next=head;
}
return newhead;

}

return head;

}
int main() {
int n;
cin>>n;
node *head=NULL;
for(int i=0;i<n;i++){
int x;
cin>>x;
insertAtTail(head,x);
}

int k;
cin>>k;

node *head1=kappend(head,n-k,k);

print(head1);


return 0;

}

code: