Easy Java beat 70%(with sufficient comments)

  • 0
        public ListNode rotateRight(ListNode head, int k) {
            if(head==null||head.next==null) return head;
             int len=length(head);
             k=k%len; //if k bigger than linked list length, mod it!
            if(k==0) return head; // doesn't change anything
            ListNode cur=head;
            ListNode tail=head;
            ListNode pre=null;
            while(cur.next!=null){ // move to the end of linked list
            cur.next=head; //let it pointer to the head
            for(int i=0;i<len-k-1;i++){
            pre=tail.next; // let the begining node of right part be the new starter
            tail.next=null; // let the left part's end pointer to null
            return pre; 
        public int length(ListNode head){ // count total linked list length
            if(head==null) return 0;
            int length=1;
            return length;

Log in to reply

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