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}
.
链表重排序
先从中间段开,分为head1,head2两个链,然后将head2逆序,之后合并head1,head2
public class Solution {
public ListNode reverse(ListNode head){
if(head==null||head.next==null)
return head;
ListNode newHead = reverse(head.next);
head.next.next = head;
head.next = null;
return newHead;
}
public void reorderList(ListNode head) {
if(head==null||head.next==null)
return;
int len =0;
ListNode cur = head;
while(cur!=null){
len++;
cur=cur.next;
}
int tmpLen = (1+len)/2;
cur=head;
while(tmpLen>1){
cur=cur.next;
tmpLen--;
}
ListNode head2 = cur.next;
cur.next=null;
head2 = reverse(head2);
ListNode head1=head;
cur=null;
while(head1!=null&&head2!=null){
cur=head1.next;
head1.next=head2;
head1=cur;
cur=head2.next;
head2.next = head1;
head2=cur;
}
}
}