/**************************************************************************
*
* 61. [Rotate List](https://leetcode.com/problems/rotate-list/)
*
* Given the head of a linked list, rotate the list to the right by k places.
*
* 把尾部的k个元素平移到头部,即为旋转。结成环来旋转
*
* Example:
* nput: head = [1,2,3,4,5], k = 2
* Output: [4,5,1,2,3]
*
* 把链表结成环来解决。
**************************************************************************/
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
typedef struct ListNode NODE;
NODE *rotateRight(NODE *head, int k){
if (NULL == head || NULL == head->next || k < 1) return head;
int len = 1;
NODE *p = head;
while (p->next) {
len++;
p = p->next;
}
k = len - k % len;
if (k == len) return head;
p->next = head;
for (int i = 0; i < k; i++)
p = p->next;
head = p->next;
p->next = NULL;
return head;
}