/** * struct ListNode { * int val; * struct ListNode *next; * ListNode(int x) : val(x), next(nullptr) {} * }; */ class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param head ListNode类 * @param k int整型 * @return ListNode类 */ ListNode* rotateLinkedList(ListNode* head, int k) { if(head==NULL)//空链表的特殊情况 return head; struct ListNode * p=head; int length=0; while(p)//遍历链表求表长 { p=p->next; length++; } p=head; while(p->next)//遍历链表找到表尾 { p=p->next; } p->next=head;//使链表成为循环链表 p=head; for(int i=0;i<length-k%length;i++)//找到旋转后的表头 { p=p->next; } struct ListNode * result=p; for(int i=0;i<length-1;i++) { p=p->next; } p->next=NULL;//遍历新链表使表尾指针指空,接触循环链表 return result; } };