My Clean Java Code(With Explanation)


  • 1
    F
    public ListNode rotateRight(ListNode head, int k) {
        if (head == null || head.next ==null || k == 0){
            return head;
        }
        
        int length = getLength(head);
        if (k%length == 0){//if k%length == 0, no need to rotate
            return head;
        }
        
        ListNode prev = null;
        ListNode start = head;
        ListNode start2 = null;//new start
        
        for (int i = 0; i < length - (k%length); i++){//find the new start node
            prev = head;
            head = head.next;
        }
        
        start2 = head;
        prev.next = null;
        while (head.next != null){//find the old tail node, link it to the original start node
            head = head.next;
        }
        
        head.next = start;
        return start2;
    }
    
    private int getLength(ListNode head){
        int i = 0;
        while (head != null){
            head = head.next;
            i = i + 1;
        }
        return i;
    }

Log in to reply
 

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