143. 重排链表

143. 重排链表

class Solution {
    public void reorderList(ListNode head) {
        if(head == null || head.next == null || head.next.next == null) return;
        ListNode mid = findMid(head); // 找到中间节点
        ListNode node2 = mid.next;
        mid.next = null;
        merge(head,reverse(node2)); // 翻转后面一段链表,并与前一段链表合并
    }
    public ListNode findMid(ListNode head) {
        ListNode fast = head, slow = head;
        while(fast != null && fast.next != null) {
            fast = fast.next.next;
            slow = slow.next;
        }
        return slow;
    }
    public ListNode reverse(ListNode head) {
        if(head == null || head.next == null) return head;
        ListNode node = reverse(head.next);
        head.next.next = head;
        head.next = null;
        return node;
    }
    public ListNode merge(ListNode node1,ListNode node2) {
        if(node1 == null) return node2;
        if(node2 == null) return node1;
        ListNode next = node1.next;
        node1.next = node2;
        node2.next = merge(next,node2.next);
        return node1;
    }
}

 

上一篇:重排链表-链表143-C++


下一篇:143. 重排链表