From 35c20922653ef660671130425f3ca693c22110ea Mon Sep 17 00:00:00 2001 From: naman jain <69587706+Namanjain6152@users.noreply.github.com> Date: Sun, 2 Oct 2022 15:47:32 +0530 Subject: [PATCH] Create Namanjain6152.md --- .../rotate-linkedList/Namanjain6152.md | 50 +++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 CPP/Problems/rotate-linkedList/Namanjain6152.md diff --git a/CPP/Problems/rotate-linkedList/Namanjain6152.md b/CPP/Problems/rotate-linkedList/Namanjain6152.md new file mode 100644 index 00000000..a8accccd --- /dev/null +++ b/CPP/Problems/rotate-linkedList/Namanjain6152.md @@ -0,0 +1,50 @@ + +ListNode* reverse(ListNode* head){ + if(!head||!head->next) return head; + ListNode* next=NULL, *curr=head, *prev= NULL; + while(curr){ + next=curr->next; + curr->next=prev; + prev=curr; + curr=next; + } + return prev; + } + + + ListNode* rotateRight(ListNode* head, int k) { + if(!head||!head->next) return head; + ListNode* length= head; + int len=0; + while(length){ + length=length->next; + len++; + } + + + ListNode* fast= head,*slow=head; + int val= k%len; + + while(fast&&val>0){ + fast=fast->next; + val--; + } + if(fast==NULL){ + return reverse(head); + } + while(fast->next!=NULL){ + fast=fast->next; + slow=slow->next; + } + fast= slow->next; + slow->next=NULL; + slow=head; + ListNode* first= reverse(slow); + ListNode* second= reverse(fast); + ListNode* temp=first; + while(temp->next){ + temp=temp->next; + } + temp->next= second; + return reverse(first); + }