题解 | #旋转链表#
旋转链表
https://www.nowcoder.com/practice/1ad00d19a5fa4b8dae65610af8bdb0ed
- 计算链表长度n。
- 将链表形成循环链表,同时记录尾节点。
- 计算实际需要旋转的位置,即k对n取模。
- 找到新的头节点和尾节点,分别为原尾节点的下一个节点和第(n-k-1)个节点。
- 断开循环链表,并返回新的头节点。
import java.util.*; /* * public class ListNode { * int val; * ListNode next = null; * public ListNode(int val) { * this.val = val; * } * } */ public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param head ListNode类 * @param k int整型 * @return ListNode类 */ public ListNode rotateLinkedList (ListNode head, int k) { if (head == null || k == 0) { return head; } // 计算链表长度 int length = 1; ListNode tail = head; while (tail.next != null) { tail = tail.next; length++; } // 形成循环链表 tail.next = head; // 计算实际需要旋转的位置 k = k % length; // 找到新的头节点和尾节点 ListNode newTail = head; for (int i = 0; i < length - k - 1; i++) { newTail = newTail.next; } ListNode newHead = newTail.next; // 断开循环链表 newTail.next = null; return newHead; } }