Given a list, rotate the list to the right by k places, where k is non-negative.
For example:
Given 1->2->3->4->5->NULL
and k = 2
,
return 4->5->1->2->3->NULL
.
题目解析:
题目很好理解,但是当k>n的时候k = k%n。然后再进行,也就是要先遍历一边链表求出其长度。
有了链表以后,也不能直接找到n-k-1的结点,因为链表最后的指针还要指向头结点。但网友有个办法,遍历链表时只遍历到最后一个结点然后计算总长度。
先上自己的代码:
class Solution {
public:
ListNode *rotateRight(ListNode *head, int k) {
if(head == NULL || k <= 0)
return head;
int n = 0;
ListNode *p = head;
while(p){
p = p->next;
++n;
}
if(k%n == 0)
return head;
k = k%n; //循环找
p = head;
int i = 1;
//找到第k个节点
while(p->next && i < k){
p = p->next;
i++;
}
//这时候p一定不为NULL,因为k<n
ListNode *q = head;
p = p->next;
while(p->next != NULL){
p = p->next;
q = q->next; //p遍历完以后,指向倒数第K+1个结点
}
p->next = head;
head = q->next;
q->next = NULL;
return head;
}
};
再看网友的代码:
class Solution {
public:
ListNode *rotateRight(ListNode *head, int k)
{
if(head==NULL)return NULL;
ListNode *p=head;
int n=0;
while(p->next)
{
p=p->next;
n++;
}
n++;
k=k%n;
p->next=head; //这里就处理了尾指针
ListNode *q=head;
for(int i=0;i<n-k-1;i++)
q=q->next;
head=q->next;
q->next=NULL;
return head;
}
};