思路:找到链表的中间节点并进行反转,然后将两个链表进行合并
public void reorderList(ListNode head) {
//思路:找到中间节点,将后一部分反转,再进行合并
if(head==null||head.next==null||head.next.next==null) return;
ListNode slow=head;
ListNode fast=head;
while(fast.next!=null&&fast.next.next!=null){
slow=slow.next;
fast=fast.next.next;
}
ListNode root=reverse(slow.next);
slow.next=null;
while(root!=null){
ListNode temp=root.next;
root.next=head.next;
head.next=root;
head=root.next;
root=temp;
}
}
//反转链表
public ListNode reverse(ListNode head){
ListNode pre=null;
ListNode temp=null;
ListNode cur=head;
while(cur!=null){
temp=cur.next;
cur.next=pre;
pre=cur;
cur=temp;
}
return pre;
}