/*
* @lc app=leetcode.cn id=61 lang=cpp
*
* [61] 旋转链表
*/
// @lc code=start
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution
{
public:
ListNode *rotateRight(ListNode *head, int k)
{
if (head == nullptr || k == 0)
{
return head;
}
ListNode *p = head;
ListNode *q = head;
// 先求出链表总个数
int number = 0;
for (ListNode *k = head; k != nullptr; k = k->next)
{
number++;
}
k = k % number;
for (int i = 0; i < k; i++)
{
p = p->next;
}
while (p->next != nullptr)
{
q = q->next;
p = p->next;
}
p->next = head;
head = q->next;
q->next = nullptr;
return head;
}
};
// @lc code=end