What is wrong with my codes?


  • 0
    N

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

    my answer is:

    public class Solution {
        public ListNode rotateRight(ListNode head, int k) {
            
            if(k<0 || head==null){
                System.out.println("The list should non-empty and k should be non-negative!");
                System.exit(-1);
            }
            
            if(k==0) return head;
            
            int i = 1;
            
            ListNode q, p = head;
            while(p.next !=null){
                i++;
                p = p.next;
            }
            if(i<=k){
                System.out.println("k should be larger than the list size");
                System.exit(-1);
            }
            p.next = head;
            i-=k;
            while(i-- != 0) p = p.next;
            q = p.next;
            p.next = null;
            return q;
    
        }
    }
    

    the error is

    Submission Result: Runtime Error

    Last executed input: {}, 0


  • 0

    public class Solution {
    public ListNode rotateRight(ListNode head, int k) {

         /*error1:   head == null应该返回head/null
        if(k<0 || head==null){    */
        if(k<0){
            System.out.println("The list should non-empty and k should be non-negative!");
            System.exit(-1);
        }
    
        /*error2:返回head的情况还有当head.next==null的时候
        if(k==0) return head;*/
        if(k==0  || head==null || head.next == null) return head;
    
        int i = 1;
    
        ListNode q, p = head;
        while(p.next !=null){
            i++;
            p = p.next;
        }
        /*error3:i可以小于等于k,只要取k = k % i即可
        if(i<=k){
            System.out.println("k should be larger than the list size");
            System.exit(-1);
        }*/
        
        p.next = head;
        
        /*error:理由同error3
        i-=k;     */
        k = k % i;
        i -= k;
        
        while(i-- != 0) p = p.next;
        q = p.next;
        p.next = null;
        return q;
    
    }
    

    }


Log in to reply
 

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