将给定的单链表 L L: L_0→L_1→…→L_{n-1}→L_ nL0→L1→…→Ln−1→Ln
重新排序为:L_0→L_n →L_1→L_{n-1}→L_2→L_{n-2}→…L0→Ln→L1→Ln−1→L2→Ln−2→…
要求使用原地算法,不能改变节点内部的值,需要对实际的节点进行交换。
例如:
对于给定的单链表{10,20,30,40},将其重新排序为{10,40,20,30}.
思路:
1,找到链表的中间节点
2,反转后面的链表
3,归并的方式合并前后链表
4,注意最后需要将前链表的最后一个节点的next改为null,否则会有环
代码
private static void reorderList(ListNode head) { if (head == null || head.next == null) { return; } ListNode fast = head; ListNode slow = head; while (fast.next != null && fast.next.next != null) { fast = fast.next.next; slow = slow.next; } ListNode after = slow.next; ListNode pre = null; while (after != null) { ListNode temp = after.next; after.next = pre; pre = after; after = temp; } ListNode first = head; after = pre; while (after != null) { ListNode fTemp = first.next; ListNode aTemp = after.next; first.next = after; after.next = fTemp; first = fTemp; after = aTemp; } first.next = null; System.out.println(0); }