Fast, Efficient and Well commented Sol. C++

programming
amazon
Tags: #<Tag:0x00007f2427474648> #<Tag:0x00007f2427474508>

#1

/**

  • Definition for singly-linked list.
  • struct ListNode {
  • int val;
    
  • ListNode *next;
    
  • ListNode(int x) : val(x), next(NULL) {}
    
  • };
    /
    pair<int,ListNode
    > sz(ListNode* a)
    {
    int c=1;
    while(a->next && c++)
    a=a->next;
    return make_pair(c,a);
    }
    ListNode* Solution::rotateRight(ListNode* A, int B) {
    int n,k;
    ListNode* head=A;
    if(!A || !A->next)
    return A;
    pair<int,ListNode*> p;//We’ll store size in first and thr last node in second
    p=sz(A);
    ListNode* l=p.second;
    n=p.first;
    if(!(B%n))
    return head;//if B is a multiple of n nothing would change
    k=B%n;
    k=n-k;
    ListNode* b=head,*prev;//b will store the kth element and prev the node befor b
    while(k–)
    {
    prev=b;
    b=b->next;
    }
    prev->next=NULL;
    l->next=head;
    return b;

}