- 旋转链表
给你一个链表的头节点 head ,旋转链表,将链表每个节点向右移动 k 个位置。
示例 1:
输入:head = [1,2,3,4,5], k = 2
输出:[4,5,1,2,3]
提示:
链表中节点的数目在范围 [0, 500] 内
-100 <= Node.val <= 100 0 <= k <= 2 * 109
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* rotateRight(struct ListNode* head, int k){
//第一步就把k=0 和 节点数目为1 和 0的全部除掉
if(k==0||head==NULL||head->next==NULL)
{
return head;
}
//第二步 进行遍历链表,统计数量,并进行首尾连结
int count = 1;
struct ListNode * temp = head;
while(temp->next)
{
count++;
temp=temp->next;
}
temp->next=head;
//第三步 计算断开点 并遍历找到断开点 重新设置头尾
count =count- k%count;
temp=head;
while(count!=1)
{
temp=temp->next;
count--;
}
head=temp->next;
temp->next=NULL;
return head;
}