Skip to content

Commit 400defd

Browse files
authored
Create rotate-list.cpp
beats 96.7
1 parent 9ca992e commit 400defd

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

rotate-list.cpp

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
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+
};

0 commit comments

Comments
 (0)