143. Reorder List

来源:互联网 发布:我的世界怎么做js 编辑:程序博客网 时间:2024/06/07 18:32

  本题比较难想,关键是要找到思路。思路是按照三步来,

  1.找到中间节点,断开。

  2.把后半截单链表 反转一下一下。

  3.合并两个单链表。


public void reorderList(ListNode head) {
if(head==null){
return;
}
ListNode slow=head;
ListNode fast=head;
while(fast.next!=null && fast.next.next!=null){
slow=slow.next;
fast=fast.next.next;
}
ListNode second=slow.next;
slow.next=null;
second=reverse(second);

ListNode first=head;

while(second!=null){
ListNode firstNext=first.next;
ListNode secondNext=second.next;
first.next=second;
second.next=firstNext;
first=firstNext;
second=secondNext;
}




}

public ListNode reverse(ListNode head){
ListNode prev=null;
ListNode next=null;
while(head!=null){
next=head.next;
head.next=prev;
prev=head;
head=next;
}

return prev;
}