8000 2 · javasharper/leetcode@c296b86 · GitHub
[go: up one dir, main page]

Skip to content

Commit c296b86

Browse files
committed
2
1 parent 3bac2f5 commit c296b86

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

RotateList/RotateList.cpp

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

0 commit comments

Comments
 (0)
0