/**
* 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;
}
};
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter