个人思路总结:
这道题的难点就是如何找到那个旋转点。步骤如下: 1、遍历链表,保存长度(count) 2、找到分割点(k%count),然后将尾部向前数第K个元素作为头,原来的头接到原来的尾上
代码如下:
class Solution {
public:
ListNode
* rotateRight(ListNode
* head
, int k
) {
if(head
==nullptr
||k
==0)
return head
;
int count
= 1;
ListNode
* tmp
= head
;
ListNode
* newend
= head
;
ListNode
* newhead
= head
;
while(tmp
->next
!=nullptr
)
{
count
++;
tmp
= tmp
->next
;
}
k
= k
% count
;
while(count
-k
-1)
{
newend
= newend
->next
;
k
++;
}
tmp
->next
= newhead
;
newhead
= newend
->next
;
newend
->next
= nullptr
;
return newhead
;
}
};
转载请注明原文地址: https://yun.8miu.com/read-58683.html