File tree 1 file changed +35
-0
lines changed
1 file changed +35
-0
lines changed Original file line number Diff line number Diff line change
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
+ };
You can’t perform that action at this time.
0 commit comments