classSolution{publicvoidreorderList(ListNode head){ListNode slow = head, fast = head.next;// Find the middle// slow will be the middle// fast will be the last node or the null node after last nodewhile(fast !=null&& fast.next !=null){
slow = slow.next;
fast = fast.next.next;}ListNode second = slow.next;// Second half head
slow.next =null;// detach first half from second halfListNode prev =null;// Previous node// Reverse the second halfwhile(second !=null){// Store original next nodeListNode tmp = second.next;// Reverse the link
second.next = prev;// Move pointers
prev = second;
second = tmp;}// prev becomes the last node of second half// second becomes the null node after the last node // Attach first half with reversed second halfListNode first = head;
second = prev;while(second !=null){// Save original next nodeListNode tmp1 = first.next, tmp2 = second.next;// Link it
first.next = second;
second.next = tmp1;
first = tmp1;
second = tmp2;}}}