题目描述:
给你一个链表的头节点 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 * 109
通过次数135,446提交次数328,848
解决思路:先通过一个循环找到链表的长度length,然后用k对链表长度length求余:k%length,得到的数字就是要移动的数量。然后再用个循环来找到要移动的位置,进行断链,然后再组链。不多BB了,上代码(运行时间:0ms):
public ListNode rotateRight(ListNode head, int k) {
if (k == 0 || head == null) {
return head;
}
int length = 0;
ListNode findLengthNode = head;
while (findLengthNode != null) {
++length;
findLengthNode = findLengthNode.next;
}
int count = k%length;
if (count == 0 ||length == 1) {
return head;
}
ListNode startNode = head;
ListNode nextNode = startNode.next;
while (startNode != null) {
--length;
if (count == length) {
ListNode temp = nextNode;
while (temp.next != null) {
temp = temp.next;
}
temp.next = head;
startNode.next = null;
head = nextNode;
break;
}
startNode = startNode.next;
nextNode = nextNode.next;
}
return head;
}
}