给定一个单链表 L 的头节点 head ,单链表 L 表示为:
L0 → L1 → … → Ln - 1 → Ln
请将其重新排列后变为:
L0 → Ln → L1 → Ln - 1 → L2 → Ln - 2 → …
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public void reorderList(ListNode head) {
//1、返回中点(偏前)
ListNode mid=split(head);
ListNode l1=head;
ListNode l2=mid.next;
mid.next=null;
//2、反转l2
l2=reverse(l2);
//3、合并
merge(l1,l2);
}
public ListNode split(ListNode head){
ListNode fast=head,slow=head;
while(fast.next!=null&&fast.next.next!=null){
slow=slow.next;
fast=fast.next.next;
}
return slow;
}
public ListNode reverse(ListNode head){
ListNode pre=null,cur=head;
while(cur!=null){
ListNode next=cur.next;
cur.next=pre;
pre=cur;
cur=next;
}
return pre;
}
public void merge(ListNode l1,ListNode l2){
ListNode t1,t2;
while(l1!=null&&l2!=null){
t1=l1.next;
t2=l2.next;
l1.next=l2;
l1=t1;
l2.next=l1;
l2=t2;
}
}
}