题目链接:
https://leetcode.com/problems/rotate-list/description/
描述
Given a list, rotate the list to the right by k places, where k is non-negative.
输入
Given 1->2->3->4->5->NULL and k = 2,
输出
return 4->5->1->2->3->NULL.
样例输入
样例输出
算法思想:
此题就是要把后面的k位数移到链表头即可,目的就是找在哪里移动,思想先把链表变成环,然后找切割点即可。需要注意的是对于K大于链表长度大小的情况 取模一下即可
比如【312】当k=5的时候,输出应该为【123】等于k=k%(链表大小)时的结果
源代码
class Solution {
public:
ListNode* rotateRight(ListNode* head, int k) {
if (head == NULL || k == 0)
return head;
ListNode *tem = head; ListNode *tem2;
int num = 1;
while (tem->next)
{
num++;
tem = tem->next;
}
if (k > num)
{
k = k % num;
}
tem->next = head; //让链表成环
//找切割点
int pre = num - k;
while (pre--)
tem = tem->next;
head = tem->next;
tem->next = NULL;
return head;
}
};
最优源代码