题目描述
给定一个无序单链表,实现单链表的选择排序(按升序排序)。
思路
读取链表的数值到集合,用集合排序,生成新的链表。
import java.util.*;
public class Solution {
public ListNode sortInList (ListNode head) {
if(head == null){
return null;
}
ArrayList<Integer> list = new ArrayList<>();
while(head != null){
list.add(head.val);
head = head.next;
}
Collections.sort(list,new Comparator<Integer>(){
public int compare(Integer o1, Integer o2){
return o1-o2;
}
});
ListNode res = new ListNode(0);
ListNode cur = res;
for(int i = 0; i < list.size(); i++){
cur.next = new ListNode(list.get(i));
cur = cur.next;
}
cur.next = null;
return res.next;
}
}