|
| 1 | +/** |
| 2 | + * Given a linked list, reverse the nodes of a linked list k at a time and return its modified list. |
| 3 | + * <p> |
| 4 | + * k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is. |
| 5 | + * <p> |
| 6 | + * You may not alter the values in the nodes, only nodes itself may be changed. |
| 7 | + * <p> |
| 8 | + * Only constant memory is allowed. |
| 9 | + * <p> |
| 10 | + * For example, |
| 11 | + * Given this linked list: 1->2->3->4->5 |
| 12 | + * <p> |
| 13 | + * For k = 2, you should return: 2->1->4->3->5 |
| 14 | + * <p> |
| 15 | + * For k = 3, you should return: 3->2->1->4->5 |
| 16 | + * <p> |
| 17 | + * Created by drfish on 16/04/2017. |
| 18 | + */ |
| 19 | +public class _25ReverNodesInkGroup { |
| 20 | + public ListNode reverseKGroup(ListNode head, int k) { |
| 21 | + if (head == null || k <= 1) |
| 22 | + return head; |
| 23 | + ListNode dummy = new ListNode(-1); |
| 24 | + dummy.next = head; |
| 25 | + for (ListNode prev = dummy, end = head; end != null; end = prev.next) { |
| 26 | + for (int i = 1; i < k && end != null; i++) |
| 27 | + end = end.next; |
| 28 | + if (end == null) |
| 29 | + break; |
| 30 | + prev = reverse(prev, prev.next, end); |
| 31 | + } |
| 32 | + return dummy.next; |
| 33 | + } |
| 34 | + |
| 35 | + private ListNode reverse(ListNode prev, ListNode start, ListNode end) { |
| 36 | + ListNode endNext = end.next; |
| 37 | + for (ListNode p = start, cur = p.next, next = cur.next; |
| 38 | + cur != endNext; |
| 39 | + p = cur, cur = next, next = next != null ? next.next : null) |
| 40 | + cur.next = p; |
| 41 | + start.next = endNext; |
| 42 | + prev.next = end; |
| 43 | + return start; |
| 44 | + } |
| 45 | +} |
0 commit comments