forked from striver79/SDESheet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrotateListCpp
35 lines (30 loc) · 871 Bytes
/
rotateListCpp
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
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* rotateRight(ListNode* head, int k) {
// edge cases
if (!head || !head->next || k == 0) return head;
// compute the length
ListNode *cur = head;
int len = 1;
while (cur->next && ++len)
cur = cur->next;
// go till that node
cur->next = head;
k = len - k % len;
while (k--) cur = cur->next;
// make the node head and break connection
head = cur->next;
cur->next = NULL;
return head;
}
};