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 >= 0 把链表循环右移k位, 这时候链表头的位置应该在len - k + 1的位置, 那直接找到这个位置 改变next指针就解决了问题。
要注意判断k等于0,k大于链表长度的情况,取模运算即可。
/**
* 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) {
if (head == NULL || head->next == NULL) return head;
ListNode *ptr = head, *tail = NULL;
int len = 0;
while (ptr)
{
tail = ptr;
ptr = ptr->next;
++len;
}
k = k % len;
if (k == 0) return head;
ptr = head;
for (int i = 0; i < len - k - 1; ++i)
ptr = ptr->next;
tail->next = head;
head = ptr->next;
ptr->next = NULL;
return head;
}
};