Skip to content

Commit 45e02ee

Browse files
author
tanfanhua
committed
rotate
1 parent 9b2a601 commit 45e02ee

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed
+37
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
package com.blankj.medium._061;
2+
3+
4+
import com.blankj.structure.ListNode;
5+
6+
public class Solution {
7+
8+
public static void main(String[] args) {
9+
Solution s = new Solution();
10+
ListNode listNode = ListNode.createTestData("[1,2,3,4,5]");
11+
ListNode.print(s.rotate(listNode, 2));
12+
listNode = ListNode.createTestData("[0,1,2]");
13+
ListNode.print(s.rotate(listNode, 4));
14+
}
15+
16+
public ListNode rotate(ListNode head, int k) {
17+
if (head == null || k <= 0) {
18+
return head;
19+
}
20+
21+
int length = 1;
22+
ListNode tmp = head;
23+
while (tmp.next != null) {
24+
tmp = tmp.next;
25+
length++;
26+
}
27+
ListNode end = tmp;
28+
tmp = head;
29+
for (int i = 0; i < length - k % length - 1; i++) {
30+
tmp = tmp.next;
31+
}
32+
end.next = head;
33+
head = tmp.next;
34+
tmp.next = null;
35+
return head;
36+
}
37+
}

0 commit comments

Comments
 (0)