148. 排序链表(快慢指针 + 归并)

148. 排序链表

给你链表的头结点 head ,请将其按 升序 排列并返回 排序后的链表 。
148. 排序链表(快慢指针 + 归并)

输入:head = [4,2,1,3]
输出:[1,2,3,4]
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode sortList(ListNode head) {
        if (head == null || head.next == null) return head;
        ListNode fast = head, slow = head;
        while (fast.next != null && fast.next.next != null) {
            slow = slow.next;
            fast = fast.next.next;
        }
        // find the mid
        ListNode mid = slow.next;
        //cut the list to half
        slow.next = null;
        ListNode l = sortList(head);
        ListNode r = sortList(mid);
        //merge linkedlist
        return merge(l, r);
    }
    public ListNode merge (ListNode l, ListNode r) {
        ListNode head = new ListNode(0);
        ListNode tmp = head;
        while (l != null && r != null) {
            if (l.val <= r.val) {
                tmp.next = l;
                l = l.next;
            } else {
                tmp.next = r;
                r = r.next;
            }
            tmp = tmp.next;
        }
        if (l != null) {
            tmp.next = l;
        } else if (r != null) {
            tmp.next = r;
        }
        return head.next;
    }
}
上一篇:SpringMVC 拦截器 Interceptor


下一篇:面试题 02.07. 链表相交