本文共 2179 字,大约阅读时间需要 7 分钟。
class Solution { /** * 逆转链表,返回头尾 * @param head * @return */ private static ListNode[] reverse(ListNode head, ListNode end) { if (head == null) { return new ListNode[2]; } ListNode[] result = new ListNode[2]; result[1] = head; ListNode pre = null; ListNode next; ListNode tail = end.next; while (head != tail) { next = head.next; head.next = pre; pre = head; head = next; } result[0] = pre; return result; } private static ListNode function(ListNode head, int k) { if (k < 2) { return head; } ListNode pre = null; ListNode result = null; ListNode start = head; int index = 1; while (head != null) { ListNode next = head.next; if (index % k == 0) { ListNode[] reverse = reverse(start, head); // result == null,则此时为第一段 if (result == null) { result = reverse[0]; } else { pre.next = reverse[0]; } pre = reverse[1]; pre.next = next; start = next; } ++ index; head = next; } return result; } private static void print(ListNode head) { while (head != null) { System.out.println(head.val); head = head.next; } } public static void main(String[] args) { ListNode n1 = new ListNode(1); ListNode n2 = new ListNode(2); ListNode n3 = new ListNode(3); ListNode n4 = new ListNode(4); ListNode n5 = new ListNode(5); ListNode n6 = new ListNode(6); ListNode n7 = new ListNode(7); ListNode n8 = new ListNode(8); n1.next = n2; n2.next = n3; n3.next = n4; n4.next = n5; n5.next = n6; n6.next = n7; n7.next = n8; ListNode head = function(n1, 8); print(head); }}class ListNode { int val; ListNode next; ListNode(int x) { val = x; }}
转载于:https://blog.51cto.com/tianyiya/2339518