struct ListNode* rotateLinkedList(struct ListNode* head, int k )
{
if ( head == NULL ) return NULL;
struct ListNode* temp = head;
struct ListNode* tail = NULL;
struct ListNode* newtail = NULL;
struct ListNode* newhead = NULL;
//记录断开节点的前后两个节点,以及原本链表的最后一个节点,最后重新排序即可
int len = 0;
while ( temp ) { //寻找链表结尾以及计算链表长度
++len;
if ( !temp->next ) tail = temp;
temp = temp->next;
}
if ( k == len ) return head; //k 和 链表长度一样不用操作
temp = head;
k = k % len; //k 大于 链表长度需要取余
for ( int i = 0; i < len - k - 1; ++i ) { //寻找需要断开的节点前后的两个点
temp = temp->next;
}
newtail = temp;
newhead = temp->next;
newtail->next = NULL;
tail->next = head;
return newhead;
}