My java accept code


  • 0
    W

    public class Solution {
    public ListNode rotateRight(ListNode head, int k) {
    if(head==null||head.next==null||k==0)
    return head;
    int totalLength=0;
    ListNode h1 = head;
    while(h1!=null){
    totalLength++;
    h1 = h1.next;
    }
    while(totalLength<=k)
    k = k-totalLength;
    if(k==0||totalLength==k)
    return head;
    ListNode h2 = head;
    while(totalLength>k+1){
    h2 = h2.next;
    totalLength--;
    }
    ListNode iner = h2.next;
    h2.next = null;
    ListNode in = iner;
    while(in.next!=null)
    in = in.next;
    in.next = head;
    return iner;
    }
    }


  • 0
    W

    infact,totalLength is not neccessary set as smaller or equals than k at the cycling "while(totalLength<=k)", it could be just set as totalLength<k


Log in to reply
 

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