题解 | #重排链表#
重排链表
http://www.nowcoder.com/practice/3d281dc0b3704347846a110bf561ef6b
/** * Definition for singly-linked list. * class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */ import java.util.*; public class Solution { public void reorderList(ListNode head) { //递归出口:未插入链表不足三位,无需插入 if(head == null) return; if(head.next == null) return ; if(head.next.next == null) return ; //寻找未排序链表的首元素、首元素的下一个元素、尾元素,并把尾元素插入到第一二个元素中间 ListNode second = head.next; ListNode tail = second.next; ListNode pre = second; while(tail.next!=null){ pre = tail; tail = tail.next; } //切断尾元素 pre.next = null; head.next = tail; tail.next = second; //重定位未排序部分链表的首元素 head = second; //递归插入 reorderList(second); } }