给定一个单链表 L:L0→L1→…→Ln-1→Ln ,
    将其重新排列后变为: L0→Ln→L1→Ln-1→L2→Ln-2→…

    你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。

    示例 1:

    给定链表 1->2->3->4, 重新排列为 1->4->2->3.

    示例 2:

    给定链表 1->2->3->4->5, 重新排列为 1->5->2->4->3.

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/reorder-list

    思路:
    使用快慢指针找到链表中点,然后翻转后半个链表,将两部分链表合并
    复杂度分析:
    时间复杂度O(n)
    空间复杂度O(1)

    1. var reorderList = function(head) {
    2. if(!head)return null;
    3. const merge = (l1,l2)=>{
    4. let l1_tmp,l2_tmp;
    5. while(l1 && l2){
    6. l1_tmp = l1.next;
    7. l2_tmp = l2.next;
    8. l1.next = l2;
    9. l1 = l1_tmp;
    10. l2.next = l1;
    11. l2 = l2_tmp;
    12. }
    13. }
    14. const reverse = (head)=>{
    15. let pre;
    16. let cur = head;
    17. while(cur){
    18. let next = cur.next;
    19. cur.next = pre;
    20. pre = cur;
    21. cur = next;
    22. }
    23. return pre;
    24. }
    25. const getMid = (head)=>{
    26. let fast = head;
    27. let slow = head;
    28. while(slow.next &&fast.next&&fast.next.next ){
    29. fast = fast.next.next;
    30. slow = slow.next;
    31. }
    32. return slow;
    33. }
    34. let l1 = head;
    35. let mid = getMid(head);
    36. let l2 = mid.next;
    37. mid.next = null;
    38. l2 = reverse(l2);
    39. merge(l1,l2);
    40. return l1;
    41. };