Given a singly linked list L: L0→L1→…→Ln-1→Ln,
reorder it to: L0→Ln→L1→Ln-1→L2→Ln-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}
.
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ public class Solution { public void reorderList(ListNode head) { //本题注意将slow和fast划分成两个链表时,注意最后一个节点的处理,下面的算法是两个表公用了一个尾节点 //也可以把两个尾节点都置null //本题需要针对节点个数的奇偶分别进行考虑,举例子!! if(head==null||head.next==null||head.next.next==null) return; ListNode fast=head; ListNode slow=head; while(fast!=null&&fast.next!=null){ fast=fast.next.next; slow=slow.next; } fast=head; ListNode head2=reverse(slow);//reverse slow list ListNode head2last=head2; //merge slow and head while(fast!=head2last&&fast.next!=head2last){ head2last=head2.next; head2.next=fast.next; fast.next=head2; fast=head2.next; head2=head2last; } return; } public ListNode reverse(ListNode node){ ListNode pre=node; ListNode last=null; while(node!=null){ pre=node.next; node.next=last; last=node; node=pre; } return last; } }