Rotate List

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

 ListNode* rotateRight(ListNode* head, int k) {
        //edge cases
        if(!head || !head->next || k==0 )return head;
        
        int n=1;//to count length of linkedlist
        ListNode* temp=head;
        while(temp->next){
            temp=temp->next;
            n++;
        }
        temp->next=head; //point last node to head (circular)
        
        k=k%n; //to manage the case when k is more than length
        k=n-k;
        
        while(k--){
            temp=temp->next;  
        }
        
       head=temp->next;
       temp->next=NULL;
        
        return head;
    }

Comments

Popular posts from this blog

Perfect Peak of Array

Is Rectangle?

Sort array with squares!