Linked List-K Append

#include
using namespace std;

class node
{
public:
long long int data;
node* next;

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

};

void insertAtTail(node* &head,long long int data)
{
if(head==NULL)
{
head=new node(data);
return;
}

node* n=new node(data);
node* temp=head;

while(temp->next!=NULL)
{
    temp=temp->next;
}

temp->next=n;
n->next=NULL;

}
long long int length(node *head)
{
int len=0;
node *temp=head;

while(temp->next!=NULL)
{
    len++;
    temp=temp->next;
}
return len;

}

void display(node* head)
{
node* temp=head;
while(temp!=NULL)
{
cout<data<<" ";
temp=temp->next;
}
cout<<endl;
}
node* kappend(node* &head,long long int k)
{
node* newHead;
node* newTail;
node*tail=head;

long long int l=length(head);
long long int count=0;

while(tail->next!=NULL)
{
    if(count==l-k)
    {
        newTail=tail; 
    }
    if(count==l-k+1)
    {
        newHead=tail; 
    }
    tail=tail->next;
    count++;

}

newTail->next=NULL;
tail->next=head; 

 return newHead;  

}

int main()
{
node* head=NULL;
long long int N,K,data;
cin>>N;

for (int i=0;i<N;i++)
{
cin>>data;
insertAtTail(head,data);
}

cin>>K;

if(K==0 || K%N==0)
{
display(head);
}
else
{
node* newhead=kappend(head,K%N);
display(newhead);
}

}

Doubt : I am not understanding why it is showing me error as MLE for two test cases? What is the meaning of MLE ?

hi @shaileshdkalkar
do mod with size of list
suppose k is 1000 and n is 5 then u dont need to rotate any no of time right as it if a factor of 5 it will be eqv to 0 rotations, so after taking k as input do
k %= n;

1 Like

cin>>K;

K=K%N;

if(K==0)
{
display(head);
}
else
{
node* newhead=kappend(head,K);
display(newhead);
}

I have changed the value of K =K%N after taking K as input.But still it is giving me MLE error for same test cases.Please check code

hi @shaileshdkalkar refer