61. Rotate List

PHOTO EMBED

Sun Feb 12 2023 06:09:31 GMT+0000 (Coordinated Universal Time)

Saved by @Ranjan_kumar #c++

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* rotateRight(ListNode* head, int long long k) {
        if(head==NULL||k==0) return head;
        int long long c=0;
        ListNode* p=head;
        while(p!=NULL)
        {
            c++;
            p=p->next;
        }
        if(c==1||k%c==0) return head;
        int r=k%c;
        int t=(c-r)-1;
        ListNode* i1=head;
        ListNode* i2;
        while(t--)
        {
            i1=i1->next;
        }
        
        if(i1) i2=i1->next;
        
        ListNode* p5=head;
        while(p5->next!=NULL)
        {
            p5=p5->next;
        }
        p5->next=head;
        if(i1) i1->next=NULL;
        
        head=i2;
        return head;
    }
};
content_copyCOPY

https://leetcode.com/problems/rotate-list/