编辑代码

/*
 * function ListNode(x){
 *   this.val = x;
 *   this.next = null;
 * }
 */
/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 *
 * 
 * @param head ListNode类 the head node
 * @return ListNode类
 */
function sortInList( head ) {
    if(!head || !head.next){
        return head;
    }
    head = quickSort(head)
    return head;
}
//快速排序
function quickSort(head) {
    if(!head || !head.next){
        return head;
    }
    let left = null;
    let leftP = left
    let right = null;
    let rightP = right;
    let middle = new ListNode(head.val);
    let p = head.next;
    while(p){
        let next = p.next;
        if(p.val<middle.val){
            //分到左边
            if(left){
                leftP.next = p;
                p.next = null;
                leftP = p;
            }else{
                left = p;
                p.next = null;
                leftP = left;
            }
        }else{
            //分到右边
            if(right){
                rightP.next = p;
                p.next = null;
                rightP = p;
            }else{
                right = p;
                p.next = null;
                rightP = right;
            }
        }
        p = next;
    }
    left = quickSort(left);
    right = quickSort(right);
    //console.log("left: ",left)
    //console.log("middle: ",middle)
    //console.log("right: ",right)
    //连接middle与right
    middle.next = right;
    right = middle;
    //连接left与right
    let p2 = left;
    while(p2 && p2.next){
        p2 = p2.next;
    }
    if(p2){
        p2.next = right;
    }else{
        left = right;
    }
    head = left;
    return head;
}
//选择排序
function selectSort( head ) {
    if(!head || !head.next){
        return head;
    }
    let Index = head;
    while(Index){
        //寻找最小值
        let minIndex = Index;
        let minP = Index;
        while(minP){
            if(minP.val <= minIndex.val){
                minIndex = minP;
            }
            minP = minP.next;
        }
        //交换
        if(Index.val > minIndex.val){
            let temp = minIndex.val;
            minIndex.val = Index.val;
            Index.val = temp;
        }
        Index = Index.next;
    }
    return head;
}
module.exports = {
    sortInList : sortInList
};