Rotate a singly linked list by k nodes.
Initially got WA, then realized k needs to be taken modulo the list length.
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
| class Solution {
public:
ListNode *rotateRight(ListNode *head, int k) {
int height = heightList(head);
if(height == 0)return head;
k %= height;
if(height < k || head == NULL || head->next == NULL || k == 0)return head;
k = height - k;
ListNode * before = head;
ListNode * now = head->next;
k--;
while(k > 0) {
k--;
before = now;
now = now->next;
}
ListNode * tmp = head;
while(tmp->next != NULL) {
tmp = tmp->next;
}
tmp->next = head;
before->next = NULL;
return now;
}
private:
int heightList(ListNode * head) {
int height = 0;
while(head != NULL) {
head = head->next;
height++;
}
return height;
}
};
|