题目描述
Given a singly linked list L: L 0→L 1→…→L n-1→L n,
reorder it to: L 0→L n →L 1→L n-1→L 2→L n-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}.
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public void reorderList(ListNode head) {
if(head == null){
return;
}else{
if(head.next == null || head.next.next == null){
return;
}
}
ListNode fast = head;
ListNode slow = head;
while(fast.next != null && fast.next.next != null){
fast = fast.next.next;
slow = slow.next;
}
ListNode after = slow.next;
slow.next = null;
ListNode pre = null;
while(after != null){
ListNode next = after.next;
after.next = pre;
pre = after;
after = next;
}
//反转过链表之后,after已经到了null,此时的pre才是新链表的头节点
after = pre;
while(head != null && after != null){
ListNode headnext = head.next;
ListNode afternext = after.next;
head.next = after;
head = headnext;
after.next = head;
after = afternext;
}
}
}