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
.
Subscribe to see which companies asked this question.
边界
1.考虑k=0/size-1;
2.size = 0/1
size=1时尾部连接问题;此处可以考虑先遍历将链表首尾相连;
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* rotateRight(ListNode* head, int k) {
ListNode* head1 = head;
if(head == NULL )
{
return head;
}
int num = 0;
while(head1->next != NULL)
{
head1 = head1->next;
num ++;
}
head1->next = head;
num ++;
k = k % num;
k = num - k - 1;
head1 = head;
int i = 0;
for(; i < k; i ++)
{
head1 = head1 ->next;
}
head = head1 -> next;
head1->next = NULL;
return head;
}
};