# 旋转链表
给你一个链表的头节点 head
,旋转链表,将链表每个节点向右移动 k
个位置。
示例 1:
输入:head = [1,2,3,4,5], k = 2
输出:[4,5,1,2,3]
示例 2:
输入:head = [0,1,2], k = 4
输出:[2,0,1]
提示:
- 链表中节点的数目在范围
[0, 500]
内 -100 <= Node.val <= 100
0 <= k <= 2 * 109
以下错误的选项是?
## aop
### before
```cpp
#include
using namespace std;
struct ListNode
{
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
```
### after
```cpp
```
## 答案
```cpp
class Solution
{
public:
ListNode *rotateRight(ListNode *head, int k)
{
if (!head || !head->next || k == 0)
return head;
int len = 1;
ListNode *cur = head;
while (cur->next && ++len)
cur = cur->next;
cur->next = head;
k = (len - k) % len;
while (k--)
cur = cur->next;
head = cur->next;
cur->next = nullptr;
return head;
}
};
```
## 选项
### A
```cpp
class Solution
{
public:
ListNode *rotateRight(ListNode *head, int k)
{
if (k == 0 || !head || !(head->next))
return head;
ListNode *temp = head;
int len = 0;
while (temp)
{
++len;
temp = temp->next;
}
k = k % len;
temp = head;
for (int i = len - 1; i > 0; --i)
temp = temp->next;
temp->next = head;
temp = head;
for (int j = len - k; j > 0; --j)
temp = temp->next;
head = temp;
for (int m = len - 1; m > 0; --m)
temp = temp->next;
temp->next = nullptr;
return head;
}
};
```
### B
```cpp
class Solution
{
public:
ListNode *rotateRight(ListNode *head, int k)
{
if (head == NULL)
return head;
ListNode *p = head;
ListNode *q = head;
int len = 1;
while (p->next)
{
len++;
p = p->next;
}
k %= len;
if (k == 0)
return head;
p->next = head;
int index = 1;
while (index < (len - k))
{
index++;
q = q->next;
}
ListNode *ret = q->next;
q->next = NULL;
return ret;
}
};
```
### C
```cpp
class Solution
{
public:
ListNode *rotateRight(ListNode *head, int k)
{
if (!head || !k || !head->next)
return head;
ListNode *temp = head;
int n;
for (n = 1; temp->next != NULL; n++)
{
temp = temp->next;
}
temp->next = head;
ListNode *Node = head;
for (int i = 0; i < n - k % n - 1; i++)
{
Node = Node->next;
}
ListNode *new_head = Node->next;
Node->next = NULL;
return new_head;
}
};
```