61. 旋转链表
给你一个链表的头节点 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 * 10^9*
解答思路:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* rotateRight(struct ListNode* head, int k){
//当链表为空或者链表只有一个元素或者移动0步的时候的情况
if (head == NULL || head->next == NULL || k == 0){
return head;
}
//创建一个虚拟头节点,指向head
struct ListNode *newhead = (struct ListNode*)malloc(sizeof(struct ListNode));
newhead->next = head;
//求出链表长度
int len = 1;
struct ListNode *cur = head;
while (cur->next != NULL){
cur = cur->next;
len++;
}
//进行头尾相连
cur->next = head;
//求出链表形成的环实际要走的步数a
int a = len-k%len;
//开始循环a步
while (a != 0){
newhead->next = newhead->next->next;
a--;
}
//将新头节点的上一个节点的next域置为空,使其从环再次变为链表
cur = newhead->next;
while (cur->next != newhead->next){
cur = cur->next;
}
cur->next = NULL;
//返回newhead的下一个节点,即是新的头节点
return newhead->next;
}