File tree Expand file tree Collapse file tree 1 file changed +47
-0
lines changed Expand file tree Collapse file tree 1 file changed +47
-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
+ int getListLength (ListNode* curr) {
14
+ int fin = 0 ;
15
+ while (curr != NULL ) {
16
+ fin++;
17
+ curr = curr->next ;
18
+ }
19
+ return fin;
20
+ }
21
+
22
+ ListNode* rotateRight (ListNode* head, int k) {
23
+ int len = getListLength (head);
24
+ if (len == 0 ) {
25
+ return head;
26
+ }
27
+ k = k % len;
28
+ if (k == 0 ) {
29
+ return head;
30
+ }
31
+
32
+ ListNode* secondHalfTail = head;
33
+ for (int i = 0 ; i < (len - 1 ) - k; i++) {
34
+ secondHalfTail = secondHalfTail->next ;
35
+ }
36
+
37
+
38
+ ListNode* firstHalfHead = secondHalfTail->next ;
39
+ ListNode* finalVal = firstHalfHead;
40
+ secondHalfTail->next = NULL ;
41
+ while (firstHalfHead->next != NULL ) {
42
+ firstHalfHead = firstHalfHead->next ;
43
+ }
44
+ firstHalfHead->next = head;
45
+ return finalVal;
46
+ }
47
+ };
You can’t perform that action at this time.
0 commit comments