61. 旋转链表

image.png
image.png

题解

形成环、截断

image.png
image.png

  1. class Solution {
  2. public ListNode rotateRight(ListNode head, int k) {
  3. if (k == 0 || head == null || head.next == null) {
  4. return head;
  5. }
  6. int count = 1;
  7. ListNode tail = head;
  8. while (tail.next != null) { // 遍历整个链表,求出链表长度 count
  9. tail = tail.next;
  10. count++;
  11. }
  12. k = k % count; // 由于 k 可能很大,为了避免不必要的计算,可以将 k 取余
  13. ListNode p = head;
  14. for (int i = 0; i < count - k - 1; i++) { // 找到第 count - k 个节点
  15. p = p.next;
  16. }
  17. tail.next = head;
  18. head = p.next;
  19. p.next = null;
  20. return head;
  21. }
  22. }