c++ easy ratate single linked list in two pass
/**
 * 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 k) {
        if(head==NULL||head->next==NULL)return head;
        int count=1;
        ListNode *cur=head;
        while(cur->next){
            cur=cur->next;
            count++;
        }
        if(k%count==0)return head;
        cur->next=head;//make a circle
        k%=count;
        for(int i=0;i<count-k;++i){
            cur=cur->next;
        }
        head=cur->next;
        cur->next=NULL;//untie the circle
        return head;
    }
};
Comments (0)