#include <stdio.h>
struct ListNode
{
int val;
struct ListNode *next;
};
struct ListNode* rotateRight(struct ListNode* head, int k)
{
if(head==NULL)
{
return NULL;
}
int rotaNums,locate,len=1;
struct ListNode *cur=head,*tail,*dmyNode;
dmyNode=malloc(sizeof(struct ListNode));
dmyNode->next=head;
//计算节点个数
while(cur->next!=NULL)
{
len++;
cur=cur->next;
}
//定位尾节点
tail=cur;
//计算实际上需要旋转的次数
rotaNums=k%len;
locate=len-rotaNums;
if(rotaNums==0)
{
return head;
}
//locate是定位到需要切割的节点
cur=dmyNode;
while(locate)
{
cur=cur->next;
locate--;
}
//重新拼接
dmyNode->next=cur->next;
cur->next=NULL;
tail->next=head;
return dmyNode->next;
}
力扣C语言-61. 旋转链表
最新推荐文章于 2025-08-04 20:35:07 发布