/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
int getLength(struct ListNode* head)
{
struct ListNode* p=head;
int i=0;
while(p!=NULL)
{
i+=1;
p=p->next;
}
return i;
}
struct ListNode* shiftRightOneStep(struct ListNode* head)
{
struct ListNode* pre,*p;
if(head!=NULL)
{
pre=head;
p=head->next;
}
//将p移动到最后一个节点
while(p->next!=NULL)
{
p=p->next;
pre=pre->next;
}
pre->next=NULL;
p->next=head;
head=p;
return head;
}
struct ListNode* rotateRight(struct ListNode* head, int k){
//如果链表长度为0 或者 1直接返回
if(getLength(head)==0||getLength(head)==1)
{
return head;
}
if(k==0)
{
return head;
}
if(k==getLength(head))
{
return head;
}
int i=0;
while(i<k%getLength(head))
{
head=shiftRightOneStep(head);
i++;
}
return head;
}
LeetCode:061. 旋转链表
最新推荐文章于 2024-05-03 18:05:14 发布