-
Notifications
You must be signed in to change notification settings - Fork 0
/
Solution.hpp
43 lines (39 loc) · 901 Bytes
/
Solution.hpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#include "../Unity/ListNode.hpp"
class Solution {
public:
ListNode *rotateRight(ListNode *head, int k)
{
if (head == nullptr || head->next == nullptr || k <= 0)
{
return head;
}
unsigned int size = 0;
auto NewHead = head;
while (NewHead != nullptr)
{
++size;
NewHead = NewHead->next;
}
k %= size;
if (k == 0)
{
return head;
}
NewHead = head;
auto LastNode = head;
while (k != 0)
{
LastNode = LastNode->next;
--k;
}
while (LastNode->next != nullptr)
{
NewHead = NewHead->next;
LastNode = LastNode->next;
}
auto temp = NewHead->next;
NewHead->next = nullptr;
LastNode->next = head;
return temp;
}
};