package leetcode;

/**
 * https://leetcode.com/problems/rotate-list/
 */
public class Problem61 {
    public static class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
        }
    }

    public ListNode rotateRight(ListNode head, int k) {
        if (head == null || k == 0) {
            return head;
        }
        int size = 0;
        for (ListNode node = head; node != null; node = node.next) {
            size++;
        }
        if (size <= k) {
            return head;
        }
        int n = size - k - 1;
        ListNode node = head;
        for (int i = 0; i < n; i++) {
            node = node.next;
        }
        ListNode newHead = node.next;
        node.next = null;
        ListNode tail = newHead.next;
        if (tail != null) {
            while (tail.next != null) {
                tail = tail.next;
            }
        }
        if (tail != null) {
            tail.next = head;
        } else {
            newHead.next = head;
        }
        return newHead;
    }
    
    public static void main(String[] args) {
        Problem61 prob = new Problem61();
        
        for (int i = 1; i <= 5; i++) {
            ListNode node = new ListNode(1);
            node.next = new ListNode(2);
            node.next.next = new ListNode(3);
            node.next.next.next = new ListNode(4);
            node.next.next.next.next = new ListNode(5);
            node = prob.rotateRight(node, i);
            for (ListNode n = node; n != null; n = n.next) {
                System.out.print(n.val + " ");
            }
            System.out.println();
        }
    }
}

@@ -315,22 +315,12 @@
 null
- %7C%7C k == 0
 ) %7B%0A
+
     
@@ -483,21 +483,40 @@
     
-if (size %3C= k
+k = k %25 size;%0A        if (k == 0
 ) %7B%0A
@@ -1026,32 +1026,32 @@
 head;%0A        %7D%0A
+
         return n
@@ -1068,603 +1068,6 @@
   %7D%0A
-    %0A    public static void main(String%5B%5D args) %7B%0A        Problem61 prob = new Problem61();%0A        %0A        for (int i = 1; i %3C= 5; i++) %7B%0A            ListNode node = new ListNode(1);%0A            node.next = new ListNode(2);%0A            node.next.next = new ListNode(3);%0A            node.next.next.next = new ListNode(4);%0A            node.next.next.next.next = new ListNode(5);%0A            node = prob.rotateRight(node, i);%0A            for (ListNode n = node; n != null; n = n.next) %7B%0A                System.out.print(n.val + %22 %22);%0A            %7D%0A            System.out.println();%0A        %7D%0A    %7D%0A
 %7D%0A

Solve problem 61