您的位置:首页 > 其它

148. Sort List

2016-04-18 19:50 423 查看

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;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: