-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathsolution061.cpp
More file actions
79 lines (69 loc) · 1.39 KB
/
solution061.cpp
File metadata and controls
79 lines (69 loc) · 1.39 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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
/**
* Rotate List
*
* cpselvis([email protected])
* September 7th, 2016
*/
#include<iostream>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
ListNode* rotateRight(ListNode* head, int k) {
if (head == NULL || k == 0)
{
return head;
}
ListNode *dummy = new ListNode(-1);
dummy -> next = head;
ListNode *fast = head, *slow = head;
int listCount = countListLength(head);
k %= listCount;
while (k --)
{
fast = fast -> next;
}
while (fast -> next)
{
fast = fast -> next;
slow = slow -> next;
}
if (slow -> next == NULL)
{
return head;
}
dummy -> next = slow -> next;
fast -> next = head;
slow -> next = NULL;
return dummy -> next;
}
int countListLength(ListNode *head)
{
int count = 0;
while (head != NULL)
{
head = head -> next;
count ++;
}
return count;
}
};
int main(int argc, char **argv)
{
ListNode *head = new ListNode(1);
head -> next = new ListNode(2);
// head -> next -> next = new ListNode(3);
//head -> next -> next -> next = new ListNode(4);
//head -> next -> next -> next -> next = new ListNode(5);
Solution s;
ListNode *ret = s.rotateRight(head, 2);
while (ret != NULL)
{
cout << ret -> val << endl;
ret = ret -> next;
}
}