题目链接
思路:
首先拿到链表的长度length,向右移动k位,也就是将最后的 k %length 个节点直接移动到链表的开头即可。
需要找到倒数第 k % length 个节点以及其前一个节点,此节点为新链表的头部,其前一个节点用于断链。
public ListNode rotateRight(ListNode head, int k) {
if (head == null || head.next == null || k <= 0) {
return head;
}
int length = 0;
ListNode cur = head;
// 统计链表长度
while (cur != null) {
length++;
cur = cur.next;
}
// 统计需要移动的节点数
int count = k % length;
if (count == 0) {
return head;
}
// cur节点从头开始向后走count步
cur = head;
ListNode pre = head;
while (count != 0) {
cur = cur.next;
count--;
}
// cur和pre同时走,当停止时,即pre之后的节点数为count
// 这一步类似于在链表中寻找倒数第k个节点
while (cur.next != null) {
cur = cur.next;
pre = pre.next;
}
// 最后一个节点的下一个指针指向头节点
cur.next = head;
// 此刻,头节点变为最后count个节点的第一个节点,即pre.next
head = pre.next;
// 断链
pre.next = null;
return head;
}
class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}