第一个思路是先让end从头开始走k+1步;
然后再让lastK从头开始和end一起走到尾部;
最后处理并返回lastK->next。
ListNode *rotateRight(ListNode *head, int k) {
if (head == NULL || head->next == NULL) return head;
ListNode * end = head;
ListNode * lastK = head;
//find last but k+1 nodes
for (int i = 0; i < k; i++)
if (end->next) end = end->next;
else end = head;
if (end == head) return head;
while (end->next)
{
lastK = lastK->next;
end = end->next;
}
//set as head
end->next = head;
head = lastK->next;
lastK->next = NULL;
return head;
}第二种思路是先让ptr走到尾部,并记录链表的长度n;
之后让ptr和head同时走n-(k%n)步,并返回head
ListNode *rotateRight(ListNode *head, int k) {
int n = 1;
ListNode *tail = head;
if (tail == 0)
return 0;
while (tail->next)
{
tail = tail->next;
n++;
}
tail->next = head;
k = n - k % n;
while (k--)
{
head = head->next;
tail = tail->next;
n--;
}
tail->next = 0;
return head;
}
本文介绍了一种优化的链表右移K位算法,通过两种思路实现:第一种是逐个节点遍历,计算链表长度并进行移动;第二种是先找到末尾节点,再定位到正确位置进行链接。该算法适用于链表操作中的频繁右移需求,提高效率。
725

被折叠的 条评论
为什么被折叠?



