将链表的每个节点向右移动K个位置,首先找到倒数第K个位置的节点,将它以及后续的节点搬到链表的开头。
下面是C语言实现的代码:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* rotateRight(struct ListNode* head, int k){
if (head == NULL) {
return head;
}
int n = 1;
struct ListNode* p = head;
while (p->next) {
p = p->next;
n++;
}
k %= n;
n -= k;
p->next = head;
while (n--) {
p = p->next;
}
head = p->next;
p->next = NULL;
return head;
}