-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path170.h
More file actions
45 lines (40 loc) · 1.08 KB
/
170.h
File metadata and controls
45 lines (40 loc) · 1.08 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
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
/*
* @param head: the List
* @param k: rotate to the right k places
* @return: the list after rotation
*/
ListNode * rotateRight(ListNode * head, int k) {
// write your code here
if(head == nullptr || head->next == nullptr)
return head;
ListNode *left = head, *right;
int list_length = 0;
while(head != nullptr) {
head = head->next;
++list_length;
}
k %= list_length; cout << k <<endl;
head = left;
if(k == 0) return head;
for(int i = 1; i < list_length - k; i++){
head = head->next;
}
right = head->next;
head->next = nullptr;
ListNode *dummyright = right;
while(dummyright->next != nullptr)
dummyright = dummyright->next;
dummyright->next = left;
return right;
}
};