Solved using Two pointers


#1

/**

  • Definition for singly-linked list.

  • struct ListNode {

  • int val;
    
  • ListNode *next;
    
  • ListNode(int x) : val(x), next(NULL) {}
    
  • };
    /
    ListNode
    Solution::rotateRight(ListNode* A, int B) {
    if(A==NULL){
    return NULL;
    }
    if(B==0){
    return A;
    }
    if(A->next==NULL){
    return A;
    }
    ListNode *trav=A;
    int n=0;
    while(trav!=NULL){
    n++;
    trav=trav->next;
    }
    //cout<<n<<endl;
    B=B%n;
    if(B==0){
    return A;
    }
    int count=1;
    ListNode *fast=A;
    ListNode *head;
    if(n & 1==0){
    while(count<B){
    fast=fast->next;
    count++;
    }
    }
    else{
    while(count<=B){
    fast=fast->next;
    count++;
    }
    }
    ListNode *slow=A;
    while(fast->next!=NULL){
    slow=slow->next;
    fast=fast->next;
    }
    fast->next=A;
    head=slow->next;
    slow->next=NULL;

    return head;

}