# 旋转链表

<p>给你一个链表的头节点 <code>head</code> ，旋转链表，将链表每个节点向右移动 <code>k</code><em> </em>个位置。</p><p> </p><p><strong>示例 1：</strong></p><img alt="" src="https://img-service.csdnimg.cn/img_convert/c0d8ae472058ab78d44488d3d18b7d34.jpeg" style="width: 600px; height: 254px;" /><pre><strong>输入：</strong>head = [1,2,3,4,5], k = 2<strong><br />输出：</strong>[4,5,1,2,3]</pre><p><strong>示例 2：</strong></p><img alt="" src="https://img-service.csdnimg.cn/img_convert/b36376b20ad1074341ffc8bca9a32eca.jpeg" style="width: 472px; height: 542px;" /><pre><strong>输入：</strong>head = [0,1,2], k = 4<strong><br />输出：</strong>[2,0,1]</pre><p> </p><p><strong>提示：</strong></p><ul>	<li>链表中节点的数目在范围 <code>[0, 500]</code> 内</li>	<li><code>-100 <= Node.val <= 100</code></li>	<li><code>0 <= k <= 2 * 10<sup>9</sup></code></li></ul>

以下程序实现了这一功能，请你填补空白处内容：

```cpp
#include <bits/stdc++.h>
using namespace std;
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)
		{
			return head;
		}
		int len = 0;
		ListNode dummy;
		dummy.next = head;
		ListNode *tail = &dummy;
		while (tail->next != nullptr)
		{
			len++;
			tail = tail->next;
		}
		ListNode *prev = &dummy;
		ListNode *p = head;
		k = k % len;
		_______________________;
		if (p != nullptr)
		{
			prev->next = tail->next;
			tail->next = head;
			head = p;
		}
		return head;
	}
};
```

## template

```cpp
#include <bits/stdc++.h>
using namespace std;
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)
		{
			return head;
		}
		int len = 0;
		ListNode dummy;
		dummy.next = head;
		ListNode *tail = &dummy;
		while (tail->next != nullptr)
		{
			len++;
			tail = tail->next;
		}
		ListNode *prev = &dummy;
		ListNode *p = head;
		k = k % len;
		for (int i = 0; i < len - k; i++)
		{
			prev = p;
			p = p->next;
		}
		if (p != nullptr)
		{
			prev->next = tail->next;
			tail->next = head;
			head = p;
		}
		return head;
	}
};
```

## 答案

```cpp
for (int i = 0; i < len - k; i++)
{
	prev = p;
	p = p->next;
}
```

## 选项

### A

```cpp
for (int i = 0; i < len; i++)
{
	prev = p;
	p = p->next;
}
```

### B

```cpp
for (int i = 0; i < len - k; i++)
{
	p = p->next;
	prev = p;
}
```

### C

```cpp
for (int i = 0; i < len; i++)
{
	p = p->next;
	prev = p;
}
```