reorder it to: L 0→L n →L 1→L n-1→L 2→L n-2→…
You must do this in-place without altering the nodes' values.
For example,
Given{1,2,3,4}, reorder it to{1,4,2,3}.
public class ReorderList
{
//节点数据结构
static class ListNode
{
int val;
ListNode next;
ListNode(int x)
{
val = x;
next = null;
}
}
public static void reorderList(ListNode head)
{
if(null == head || null == head.next)
{
return;
}
//快慢指针找到中间节点
ListNode _slow = head;
ListNode _fast = head;
while( null != _fast.next && null != _fast.next.next)
{
_slow = _slow.next;
_fast = _fast.next.next;
}
//拆分链表,并反转中间节点之后的链表
//后一个链表的节点数与前一个链表相同或少一个
ListNode _after = _slow.next;
_slow.next = null;
ListNode _node = null;
//反转时,依次遍历每个节点,依次将每个节点的next指向原来的前一个节点
while(null != _after)
{
ListNode _next = _after.next;
_after.next = _node;
_node = _after;
_after = _next;
}
//合并链表
_after = _node;//后一个链表的第一个节点
ListNode _first = head;
while(null != _after)
{
ListNode _tempFirst = _first.next;
ListNode _tempAfter = _after.next;
_after.next = _first.next;
_first.next = _after;
_first = _tempFirst;
_after = _tempAfter;
}
}
}