C++ solution detect the new head of the list


  • 0
    P
      ListNode* rotateRight(ListNode* head, int k) {
            
            if(head && k > 0)
            {
                int size = 0;
        	
            	for(ListNode * tmp = head; tmp!=NULL; tmp = tmp->next)
            		size++;
            	
            	if(size > 1)
            	{
                
                    int diff = (size >= k) ? size - k : size - (k % size);
                
                	if(diff > 0 && diff < size)
                	{
                		ListNode * newHead= NULL;
                		ListNode * tmp = head;
                		for(int i = 0; i < diff; i++)
                			tmp = tmp->next;
                		newHead = tmp;
                
                		while(tmp->next != NULL)
                			tmp = tmp->next;
                		
                		tmp->next = head;
                		while(tmp->next != newHead)
                			tmp = tmp->next;
                
                		tmp->next = NULL;
                		head = newHead;
                	}
            	}
            }
            
            return head;
        }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.