File tree Expand file tree Collapse file tree 1 file changed +46
-0
lines changed Expand file tree Collapse file tree 1 file changed +46
-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(int x) : val(x), next(NULL) {}
7
+ * };
8
+ */
9
+ class Solution {
10
+ public:
11
+ ListNode *rotateRight (ListNode *head, int k) {
12
+ // Start typing your C/C++ solution below
13
+ // DO NOT write int main() function
14
+
15
+ if (head == NULL ) return head;
16
+
17
+ ListNode *node = head;
18
+ int len = 0 ;
19
+ while (node) {
20
+ len += 1 ;
21
+ node = node->next ;
22
+ }
23
+ if (k >= len)
24
+ k %= len;
25
+
26
+ if (k == 0 )
27
+ return head;
28
+
29
+ ListNode *slow = head;
30
+ ListNode *fast = head;
31
+
32
+ for (int i = 0 ; i < len - 1 ; i++)
33
+ fast = fast->next ;
34
+ for (int i = 0 ; i < len - k - 1 ; i++)
35
+ slow = slow->next ;
36
+
37
+ if (slow == fast)
38
+ return head;
39
+
40
+ ListNode *newHead = slow->next ;
41
+ slow->next = NULL ;
42
+ fast->next = head;
43
+ return newHead;
44
+
45
+ }
46
+ };
You can’t perform that action at this time.
0 commit comments