https://leetcode-cn.com/problems/rotate-list/
思路:双指针
ListNode* rotateRight(ListNode* head, int k) {
if (k == 0 || !head || !head->next) {
return head;
}
ListNode *newhead = head;
//统计拉链长度,方便后续%运算
int listnum = 0;
while(head) {
listnum += 1;
if (head->next) {
head = head->next;
} else {
break;
}
}
//cout << "num:" << listnum << " " << k % listnum << endl;
//如果循转为0词的话,直接返回拉链
k = k % listnum;
if (k == 0) {
return newhead;
}
ListNode *res = new ListNode();
ListNode *resHead;
//存储旋转前头指针
resHead = res;
res->next = newhead;
res = res->next;
//过滤旋转前头指针,位置为旋转前倒数第一个位置,方便后续断开操作
int i = 0;
while (i < listnum - k - 1) {
res = res->next;
i++;
}
//存储旋转位置头指针
ListNode *temp = res->next;
i += 1;
//找到旋转指针最后一个指针
res->next = NULL;
ListNode *temphead = temp;
while(i < listnum - 1) {
temp = temp->next;
i += 1;
}
//用旋转最后一个指针,连接旋转前第一个指针
temp->next = resHead->next;
return temphead;
}