题目链接:力扣
解题思路:k的大小可能大于链表的长度,先求解出链表的长度length,当K>=length时,只需要将链表中每个节点向右移动 k % length个位置。当k%length=0时,相当于没有移动直接返回原链表。移动节点后,需要找到新的头节点,并将新头节点的前驱与头节点断开连接,原尾节点与头节点相连
具体算法流程:
- 遍历链表,计算链表的长度length,并找到尾节点。
- k=k%lengt,如果k=0,相当于不移动,直接返回head
- 新的头节点是原链表中第length-k个节点(从0开始计数)
- 再次遍历链表,找到第length-k个节点,和其前驱
- 令前驱的next指向null,断开和新头节点的连接
- 令尾节点的next指向头节点
- 返回 新的头节点
AC代码:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public static ListNode rotateRight(ListNode head, int k) {
if (k == 0 || head == null || head.next == null) {
return head;
}
int length = 1;
ListNode end = head;
//找到尾节点
while (end.next != null) {
length++;
end = end.next;
}
k = k % length;
if (k == 0) {
return head;
}
//新节点是第newPosition的节点(从0开始计数)
int newPosition = length - k;
//新的头节点
ListNode newHead = head;
//新头节点的前驱
ListNode pre = head;
while (newPosition > 0) {
pre = newHead;
newHead = newHead.next;
newPosition--;
}
pre.next = null;
end.next = head;
return newHead;
}
}