我提交了好多次,错误莫名其妙的,到后来才明白过来,原来我把题目给理解错了。
这个题的意思不是说让你把最后的那k个位置的元素移到前面来,这种问题的做法就是用两个指针,先让一个走,走到一定的长度之后两个一起走,很简单。它实际的意思是整个链表循环右移,假设一个链表长度是N,那么循环右移N次之后,链表又变回了原来的样子。k的取值范围只说了是非负的,也就是它可以是大于N的,因此实际的移位次数只是(k%N)而已。
代码就不多说了,很简单。
class Solution {
public:
ListNode *rotateRight(ListNode *head, int k) {
if(!head||!head->next||k==0)
return head;
int i=0, len=0;
ListNode *pre=head, *pNode = head, *newHead;
while(pNode){
len++;
pNode = pNode->next;
}
pNode = head;
k %= len;
if(k == 0) return head;
while(i<k&&pNode){
pNode = pNode->next;
i++;
}
while(pNode->next){
pre = pre->next;
pNode = pNode->next;
}
newHead = pre->next;
pre->next = NULL;
pNode->next = head;
return newHead;
}
};