链表旋转链表

难度中等

题目描述

image.png

解题思路

image.png
image.png

作者:demigodliu
链接:https://leetcode-cn.com/problems/rotate-list/solution/bi-he-wei-huan-xuan-zhuan-lian-biao-by-d-3wj1/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

Code

  1. public ListNode rotateRight(ListNode head, int k) {
  2. if (k == 0 || head == null || head.next == null) {
  3. return head;
  4. }
  5. int len = 1;
  6. ListNode cur = head;
  7. while (cur.next != null) {
  8. cur = cur.next;
  9. len++;
  10. }
  11. int add = len - k % len;
  12. cur.next = head;
  13. while (add-- > 0) {
  14. cur = cur.next;
  15. }
  16. ListNode ans = cur.next;
  17. cur.next = null;
  18. return ans;
  19. }