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}
.
找到中点,反转后半部分链表。
反转经常用到应该熟悉掌握 newhead head temp
merge的时候要区分奇偶点,所以设了index 来区分奇偶 index++
注意返回的中点是后半部分链表的前一个节点,要将前半部分节点断开,下一个节点置空
public class Solution {
public void reorderList(ListNode head) {
if(head==null||head.next==null) return ;
ListNode dummy=head;
ListNode slow=findmid(head);
ListNode newhead=reverse(slow.next);
slow.next=null;
merge(dummy,newhead);
}
public ListNode findmid(ListNode head){
ListNode fast=head;
ListNode slow=head;
while(fast!=null&&fast.next!=null){
fast=fast.next.next;
slow=slow.next;
}
return slow;
}
public ListNode reverse(ListNode head){
ListNode newhead=null;
while(head!=null){
ListNode temp=head.next;
head.next=newhead;
newhead=head;
head=temp;
}
return newhead;
}
public void merge(ListNode head1,ListNode head2){
int index=0;
ListNode dummy=new ListNode(0);
while(head1!=null&&head2!=null){
if(index%2==0){
dummy.next=head1;
head1=head1.next;
}
else{
dummy.next=head2;
head2=head2.next;
}
dummy=dummy.next;
index++;
}
if(head1!=null)
dummy.next=head1;
else dummy.next=head2;
}
}