image.png

解题思路

image.png
image.png

  1. public ListNode rotateRight(ListNode head, int k) {
  2. // base cases
  3. if (head == null) return null;
  4. if (head.next == null) return head;
  5. // close the linked list into the ring
  6. ListNode old_tail = head;
  7. int n;
  8. for(n = 1; old_tail.next != null; n++)
  9. old_tail = old_tail.next;
  10. old_tail.next = head;
  11. // find new tail : (n - k % n - 1)th node
  12. // and new head : (n - k % n)th node
  13. ListNode new_tail = head;
  14. for (int i = 0; i < n - k % n - 1; i++)
  15. new_tail = new_tail.next;
  16. ListNode new_head = new_tail.next;
  17. // break the ring
  18. new_tail.next = null;
  19. return new_head;
  20. }