给你一个链表的头节点 head
,旋转链表,将链表每个节点向右移动 k
个位置。
示例 1:
输入:head = [1,2,3,4,5], k = 2 输出:[4,5,1,2,3]
示例 2:
输入:head = [0,1,2], k = 4 输出:[2,0,1]
提示:
- 链表中节点的数目在范围
[0, 500]
内 -100 <= Node.val <= 100
0 <= k <= 2 * 109
题解:
本题主要思路是将其看成一个环:当K值大于链表长度len时,K=K%len,当K值等于len时,来你表不做处理,当K值小于len时,链表在len-K出断开。
代码
struct ListNode* rotateRight(struct ListNode* head, int k) {
if(head==NULL)
{
return NULL;
}
if(head->next==NULL)
{
return head;
}
int len = 1;
struct ListNode*pmove = head;
struct ListNode*pre = head;
while(head->next!=NULL)
{
len++;
head = head->next;
}
head = pmove;
for(int i = 0;i<(len-(k%len)-1);i++)
{
head = head->next;
}
pmove = head;
for(int j = 0;j<(k%len);j++)
{
pmove = pmove->next;
}
pmove->next = pre;
pmove=head->next ;
head->next = NULL;
return pmove;
}