给定一个单链表 L 的头节点 head ,单链表 L 表示为:

    L0 → L1 → … → Ln - 1 → Ln
    请将其重新排列后变为:

    L0 → Ln → L1 → Ln - 1 → L2 → Ln - 2 → …
    不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。

    示例 1:
    image.png

    输入:head = [1,2,3,4]
    输出:[1,4,2,3]
    示例 2:
    image.png

    输入:head = [1,2,3,4,5]
    输出:[1,5,2,4,3]

    提示:

    链表的长度范围为 [1, 5 * 104]
    1 <= node.val <= 1000


    1. /**
    2. * Definition for singly-linked list.
    3. * public class ListNode {
    4. * int val;
    5. * ListNode next;
    6. * ListNode() {}
    7. * ListNode(int val) { this.val = val; }
    8. * ListNode(int val, ListNode next) { this.val = val; this.next = next; }
    9. * }
    10. */
    11. class Solution {
    12. public void reorderList(ListNode head) {
    13. ListNode pre = new ListNode(0);
    14. ListNode fast = pre, slow = pre;
    15. pre.next = head;
    16. while(fast != null && fast.next != null){
    17. fast = fast.next.next;
    18. slow = slow.next;
    19. }
    20. ListNode next = slow.next;
    21. slow.next = null; //断开前半部分
    22. ListNode reverse_node = reverse(next);
    23. ListNode cur = pre.next;
    24. while(reverse_node != null){ //穿插
    25. ListNode reverse_next = reverse_node.next;
    26. ListNode cur_next = cur.next;
    27. cur.next = reverse_node;
    28. reverse_node.next = cur_next;
    29. cur = cur_next;
    30. reverse_node = reverse_next;
    31. }
    32. }
    33. //反转链表操作
    34. public ListNode reverse(ListNode node){
    35. ListNode pre = null;
    36. while(node != null){
    37. ListNode next = node.next;
    38. node.next = pre;
    39. pre = node;
    40. node = next;
    41. }
    42. return pre;
    43. }
    44. }