1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
| class Solution { public static ListNode nail;
public ListNode rotateRight(ListNode head, int k) { int l = 0; nail=null; for (ListNode i = head; i != null; i = i.next) { l++; if (i.next == null) { nail = i; } } if (k == 0 || l == 1||l==0) return head;
k = k % l;
for (int i = 0; i < k; i++) {
int v=nail.val; head=head_insert(v,head); delete_nail(head); } return head; }
public ListNode head_insert(int v, ListNode head) { ListNode ln = new ListNode(v); ln.next = head; return ln; }
public void delete_nail(ListNode head) {
ListNode s = head; while (s.next != nail) { s = s.next; } s.next = null; nail = s; }
}
|