链接: 旋转链表
给你一个链表的头节点 head
,旋转链表,将链表每个节点向右移动 k
个位置。
示例 1:
输入:head = [1,2,3,4,5], k = 2
输出:[4,5,1,2,3]
示例 2:
输入:head = [0,1,2], k = 4
输出:[2,0,1]
提示:
[0, 500]
内-100 <= Node.val <= 100
0 <= k <= 2 * 10^9
/**
* 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 ListNode rotateRight(ListNode head, int k) {
if (head == null) {
return null;
}
// 获取长度
ListNode lastNode = head;
int length = 0;
while (true) {
length++;
if (lastNode.next == null) {
lastNode.next = head;
break;
}
lastNode = lastNode.next;
}
// 移动
k = k % length;
int index = 0;
ListNode node = head;
while (node != null) {
index++;
if (index == length - k) {
head = node.next;
node.next = null;
break;
}
node = node.next;
}
return head;
}
}
整理完毕,完结撒花~ 🌻