-
Notifications
You must be signed in to change notification settings - Fork 27
Expand file tree
/
Copy pathRotate List.cpp
More file actions
52 lines (47 loc) · 1.13 KB
/
Rotate List.cpp
File metadata and controls
52 lines (47 loc) · 1.13 KB
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
44
45
46
47
48
49
50
51
52
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution
{
public:
ListNode* rotateRight(ListNode* head, int k)
{
ListNode dummy(0);
dummy.next = head;
ListNode* cur = head;
int count = 0;
while (cur != nullptr)
{
cur = cur->next;
count += 1;
}
if (count != 0)
{
int r = k % count;
if (r != 0)
{
r = count - r;
cur = head;
for (int i = 1; i < r; ++i)
{
cur = cur->next;
}
ListNode* first = cur->next;
cur->next = nullptr;
cur = first;
for (int i = r + 1; i < count; ++i)
{
cur = cur->next;
}
cur->next = head;
dummy.next = first;
}
}
return dummy.next;
}
};