My JAVA solution with two for loops (best time)


  • 0
    Y
    public class Solution {
        public ListNode rotateRight(ListNode head, int k) {
            if(head == null || k ==0 || head.next == null) return head;
            ListNode orig_head = head;
            int len = 0;
            while(head!=null){
                len++;
                if(head.next == null){
                    if(k%len !=0) head.next = orig_head;
                    break;
                }
                head = head.next;
            }
            if(k%len == 0) return orig_head;
            else k=len - k%len;
            int i = 0;
            head = orig_head;
            while(head!=null){
                i++;
                if(i == k){
                    orig_head = head.next;
                    head.next = null;
                    head = orig_head;
                }
                else if(i == len){
                    break;
                }
                else{
                    head = head.next;
                }
            }        
            return orig_head;
        }
    }

Log in to reply
 

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