题解 | #旋转链表#
旋转链表
https://www.nowcoder.com/practice/1ad00d19a5fa4b8dae65610af8bdb0ed
/** * struct ListNode { * int val; * struct ListNode *next; * }; */ /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param head ListNode类 * @param k int整型 * @return ListNode类 */ struct ListNode* rotateLinkedList(struct ListNode* head, int k ) { // write code here struct ListNode*fast,*slow; fast=head; slow=head; struct ListNode*temp,*p; if(head==NULL||head->next==NULL)//特殊情况 return head; p=head; int count=0; while(p!=NULL){ p=p->next; count++; } k%=count; if(k==0){//特殊 return head; } while(k!=0){//快慢指针 可以画一下图 fast=fast->next; k--; } while(fast->next!=NULL){ fast=fast->next; slow=slow->next; } fast->next=head; temp=slow->next; slow->next=NULL; return temp; }