Skip to content

Commit 3706cbe

Browse files
authored
Create rotateListCpp
1 parent 2877cd8 commit 3706cbe

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

rotateListCpp

+35
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* struct ListNode {
4+
* int val;
5+
* ListNode *next;
6+
* ListNode() : val(0), next(nullptr) {}
7+
* ListNode(int x) : val(x), next(nullptr) {}
8+
* ListNode(int x, ListNode *next) : val(x), next(next) {}
9+
* };
10+
*/
11+
class Solution {
12+
public:
13+
ListNode* rotateRight(ListNode* head, int k) {
14+
// edge cases
15+
if (!head || !head->next || k == 0) return head;
16+
17+
// compute the length
18+
ListNode *cur = head;
19+
int len = 1;
20+
while (cur->next && ++len)
21+
cur = cur->next;
22+
23+
// go till that node
24+
cur->next = head;
25+
k = len - k % len;
26+
while (k--) cur = cur->next;
27+
28+
// make the node head and break connection
29+
head = cur->next;
30+
cur->next = NULL;
31+
32+
33+
return head;
34+
}
35+
};

0 commit comments

Comments
 (0)