Given the head of a linked list, rotate the list to the right by k places.
Example 1:

image
Input: head = [1,2,3,4,5], k = 2
Output: [4,5,1,2,3]
Example 2:

image
Input: head = [0,1,2], k = 4
Output: [2,0,1]
Constraints:
- The number of nodes in the list is in the range
[0, 500]. -100 <= Node.val <= 1000 <= k <= 2 * 10<sup>9</sup>
哈哈哈哈哈哈哈 这个题目是我刷LeetCode 有史以来解决的最快的一道题目!
题目名称叫旋转链表,其实只是将尾部的结点不断的追加到链表的头部上, 如果把链表收尾相连形成一个环的话,那么各个节点的相对位置都是不发生改变的, 我们需要做的就是在K次 Rotate后 找到新的头部节点位置, 然后返回就可以了.
代码思路也很简单:
- 获取到链表的长度和尾部的节点
- 将链表的首尾相连, 形成链表环
- 计算链表新的头部位置, (这里有个取余的操作, 确保 O(n) 时间内能找到新的头部位置)
- 返回新的链表头
两次遍历, 时间复杂度为: O(n)
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
typedef struct ListNode ListNode;
struct ListNode* rotateRight(struct ListNode* head, int k){
if( !head ) return NULL;
int lengthCount = 0;
int finalStop = 0;
ListNode *headSave = head;
ListNode *tailPosition = NULL;
while(head){
lengthCount++;
tailPosition = head;
head = head->next;
}
head = headSave;
finalStop = lengthCount - (k % lengthCount) - 1;
tailPosition->next = head;
while( finalStop-- ){
head = head->next;
}
headSave = head->next;
head->next = NULL;
return headSave;
}