148. Sort List

来源:互联网 发布:手机卡 非实名 淘宝 编辑:程序博客网 时间:2024/05/29 09:56

Sort List

Sort a linked list in O(n log n) time using constant space complexity.

对一个链表排序,要求O(n log n)的时间复杂度。
因为Java提供了O(n log n)复杂度排序的算法,所以就不自己写了。。。
自己写要实现归并排序

/** * Definition for singly-linked list. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { val = x; } * } */public class Solution {    public ListNode sortList(ListNode head) {        if (head == null || head.next == null) {            return head;        }        ListNode temp = head;        List<ListNode> list = new ArrayList<>();        //把链表中的每一项添加到一个List中,然后用Collections.sort方法排序        while (temp != null) {            list.add(temp);            temp = temp.next;        }        Comparator<ListNode> comparator = new Comparator<ListNode>() {            @Override            public int compare(ListNode o1, ListNode o2) {                return o1.val - o2.val;            }        };        Collections.sort(list, comparator);        ListNode first = null;        //使自己定义的List中每一项ListNode对象的next指针指向该项的下一项        for (int i = list.size() - 1; i > 0 ; i--) {            //如果是链表中的最后一项,则让链表尾部指向null,否则会指向原链表中的未知位置            if (i == list.size() - 1) {                list.get(i).next = null;            }            ListNode pre = list.get(i - 1);            pre.next = list.get(i);            //返回头结点            if (i == 1) {                first = list.get(i - 1);            }        }        return first;    }}
0 0
原创粉丝点击