LeetCode Rotate List easy one but don't forget k=k%(no of nodes)
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* rotateRight(ListNode* head, int k) {
if(head==NULL)
return head;
ListNode* fast=head;
ListNode* slow=head;
int cnt=0;
while(fast!=NULL)
{
cnt++;
fast=fast->next;
}
if(k%cnt==0)
return head;
else
k=k%cnt;
fast=head;
while(k && fast->next){
fast=fast->next;
k--;
}
while(fast->next!=NULL)
{
fast=fast->next;
slow=slow->next;
}
fast->next=head;
head=slow->next;
slow->next=NULL;
return head;
}
};
No comments:
Post a Comment