|
2 | 2 |
|
3 | 3 | import com.fishercoder.common.classes.ListNode;
|
4 | 4 |
|
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 |
| - */ |
14 | 5 | public class _61 {
|
15 | 6 |
|
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 | + } |
36 | 30 | }
|
37 |
| - } |
38 | 31 | }
|
0 commit comments