Skip to content

148. 排序链表 #61

Description

@JesseZhao1990

image

/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */
/**
 * @param {ListNode} head
 * @return {ListNode}
 */
var sortList = function(head) {
    if(head == null || head.next == null) return head;
    let fast = head.next, slow = head;
    while (fast != null && fast.next != null) {
        slow = slow.next;
        fast = fast.next.next
    }
    let temp = slow.next;
    slow.next = null;

    let left = sortList(head)
    let right = sortList(temp)

    let h = new ListNode(0)
    let res = h
    while (left != null && right != null) {
        if (left.val < right.val) {
            h.next = left
            left = left.next
        } else {
            h.next = right
            right = right.next
        }
        h = h.next
    }
    h.next = left != null ? left : right
    return res.next

};

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions