Leetcode Sort List

来源:互联网 发布:淘宝佣金软件购买 编辑:程序博客网 时间:2024/04/26 13:53
题目:Sort a linked list in O(n log n) time using constant space complexity.
答案,源代码:
/**
 * Definition for singly-linked list.
 * class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
   public ListNode sortList(ListNode head) {
if(null==head){
return head;
}
ArrayList<ListNode> al = new ArrayList<ListNode>();
ListNode ln =head;
al.add(ln);
while (null != ln.next) {
ln=ln.next;
al.add(ln);
}
Collections.sort(al, new Comparator<ListNode>() {
@Override
public int compare(ListNode node1, ListNode node2) {
return node1.val-node2.val;
}});
ln=al.get(0);
ListNode node = ln;
for (int i = 1; i < al.size(); i++) {
node.next = new ListNode(0);
node.next.val=al.get(i).val;
node=node.next;
}
return ln;
    }

}

0 0
原创粉丝点击