clean-java-solution


  • 0
    N
    public ListNode rotateRight(ListNode head, int k) {
            if (head == null || head.next == null || k == 0) {
    			return head;
    		}
    
    		// Get the length of linked list
    		ListNode traverse = head;
    		int len = 0;
    
    		while (traverse != null) {
    			len++;
    			traverse = traverse.next;
    		}
    
    		if(k%len == 0){
                return head;
            } else {
                k = (k%len);
            }
            
    		
    		// Move front by len-k
            int noOfPlaces = len - k;
    		traverse = head;
    		int count = 1;
    		
    		while(count < noOfPlaces){
    			traverse = traverse.next;
    			count++;
    		}
    		
    		ListNode newHead = traverse.next;
    		traverse.next = null;
    		
    		traverse = newHead;
    		
    		while(traverse.next != null){
    			traverse = traverse.next;
    		}
    		
    		traverse.next = head;
    		
    		return newHead;
        }
    

Log in to reply
 

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