讨论/《高级算法》 - 排序链表/
《高级算法》 - 排序链表
共 1 个回复
/**
 * 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) {
        // 作弊的方法,转数组排序,然后重新赋值
        int [] numArr=new int[getLength(head)];
        ListNode node=head;
        for(int i=0;i<numArr.length;i++){
            numArr[i]=node.val;
            node=node.next;
        }
        Arrays.sort(numArr);
        node=head;
        for(int i=0;i<numArr.length;i++){
            node.val=numArr[i];
            node=node.next;
        }
        return head;
    }

    int getLength(ListNode node){
        int length=0;
        while(node!=null){
            node=node.next;
            length++;
        }
        return length;
    }
}