Skip to content

Commit 4e7a01a

Browse files
refactor 61
1 parent d948a61 commit 4e7a01a

File tree

1 file changed

+23
-30
lines changed
  • src/main/java/com/fishercoder/solutions

1 file changed

+23
-30
lines changed

src/main/java/com/fishercoder/solutions/_61.java

Lines changed: 23 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -2,37 +2,30 @@
22

33
import com.fishercoder.common.classes.ListNode;
44

5-
/**
6-
* 61. Rotate List
7-
*
8-
* Given a list, rotate_naive the list to the right by k places, where k is non-negative.
9-
10-
For example:
11-
Given 1->2->3->4->5->NULL and k = 2,
12-
return 4->5->1->2->3->NULL.
13-
*/
145
public class _61 {
156

16-
public static class Solution1 {
17-
//credit: https://discuss.leetcode.com/topic/26364/clean-java-solution-with-brief-explanation
18-
//link the tail of the linked list to the head to form a circle, then count to find the pint and cut it
19-
public ListNode rotateRight(ListNode head, int k) {
20-
if (head == null) {
21-
return head;
22-
}
23-
ListNode copyHead = head;
24-
int len = 1;
25-
while (copyHead.next != null) {
26-
copyHead = copyHead.next;
27-
len++;
28-
}
29-
copyHead.next = head;//link the tail and head to make it a circle
30-
for (int i = len - k % len; i > 1; i--) {
31-
head = head.next;
32-
}
33-
copyHead = head.next;
34-
head.next = null;//break the circle
35-
return copyHead;
7+
public static class Solution1 {
8+
/**
9+
* credit: https://discuss.leetcode.com/topic/26364/clean-java-solution-with-brief-explanation
10+
* link the tail of the linked list to the head to form a circle, then count to find the pint and cut it
11+
*/
12+
public ListNode rotateRight(ListNode head, int k) {
13+
if (head == null) {
14+
return head;
15+
}
16+
ListNode copyHead = head;
17+
int len = 1;
18+
while (copyHead.next != null) {
19+
copyHead = copyHead.next;
20+
len++;
21+
}
22+
copyHead.next = head;//link the tail and head to make it a circle
23+
for (int i = len - k % len; i > 1; i--) {
24+
head = head.next;
25+
}
26+
copyHead = head.next;
27+
head.next = null;//break the circle
28+
return copyHead;
29+
}
3630
}
37-
}
3831
}

0 commit comments

Comments
 (0)