Review My code - What’s wrong in this? I got 5 TLE and only two test cases were successful.
#include
using namespace std;
class node{
public:
int data;
node* next;
node(int d){
data=d;
next=NULL;
}
};
node* kthNode(node*& head, int k){
if(head->next==NULL || head==NULL){
return head;
}
node* slow=head;
node* fast=head;
while(k>1){
fast=fast->next;
k–;
}
fast=fast->next;
while(fast->next!=NULL){
fast=fast->next;
slow=slow->next;
}
node* newHead=slow->next;
slow->next=NULL;
fast->next=head;
head=newHead;
return head;
}
void insertAtTail(node*& head, int d){
if(head==NULL){
head=new node(d);
return;
}
node temp=head;
while(temp->next!=NULL){
temp=temp->next;
}
node newNode=new node(d);
temp->next=newNode;
return;
}
node take_input(int n){
int iter=0;
int d;
node head=NULL;
while(iter<n){
cin>>d;
insertAtTail(head, d);
iter++;
}
return head;
}
void print(node*& head){
node* temp = head;
while(temp!=NULL){
cout<data<<" ";
temp=temp->next;
}
return;
}
int main(){
int n1, k;
cin>>n1;
node* a=take_input(n1);
cin>>k;
node* head=kthNode(a, k);
print(head);
return 0;
}