/**
* Time complexity : O(N)
* Space complexity : O(1)
*/
class Solution {
public void reorderList(ListNode head) {
if(head == null || head.next == null) return;
// find the middle of linked lis
ListNode slow = head, fast = head;
while(fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
}
// reverse the second part of the list
ListNode prev = null, curr = slow, tmp;
while(curr != null) {
tmp = curr.next;
curr.next = prev;
prev = curr;
curr = tmp;
}
// merge two sorted linked lists
ListNode first = head, second = prev;
while(second.next != null) {
tmp = first.next;
first.next = second;
first = tmp;
tmp = second.next;
second.next = first;
second = tmp;
}
}
}