题目描述: 给你一个链表的头节点 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
忙死了…带着烦躁的心情把这题暴力解决掉: 题解: 解题思路: 1.先取值,计算出节点数 2.如果节点数 <= k, 那么 k 对 length 取个余(数目很大时缩短时间) 3.移位 4.重新赋值
struct ListNode* rotateRight(struct ListNode* head, int k){
struct ListNode* rootp = head;
int length = 0;
int temp2 = 0;
int num[500] = {0};
if(head == NULL)
return NULL;
while(head){
num[length] = head->val;
length++;
head = head->next;
}
head = rootp;
if(k >= length)
k %= length;
while(k--){
int temp = num[0];
num[0] = num[length-1];
for(int i = 1; i < length ; i++){
temp2 = num[i];
num[i] = temp;
temp = temp2;
}
}
rootp->val = num[0];
length = 0;
while(head){
head->val = num[length];
length++;
head = head->next;
}
return rootp;
}
下大雪了,纪念一下~ 2022.1.28
链接:https://leetcode-cn.com/problems/rotate-list
|