思路:双指针,先让快指针走k步,再让两个指针一起走完。把链表头接到链表尾,让慢指针的下一节点成为新链表头,要注意最后三步的处理顺序。
代码
class Solution {
public:
ListNode* rotateRight(ListNode* head, int k) {
if (!head || k == 0) return head;
int n = 0;
for (auto p = head; p; p = p->next) n ++ ; //求链表长度
k %= n;
auto p = head, q = head;
while (k -- ) q = q->next; //1
while (q->next) //2
{
q = q->next;
p = p->next;
}
q->next = head; //3
head = p->next; //4
p->next = nullptr; //5
return head;
}
};
nice 打卡
图很nice
嘻嘻😘