import java.util.*; /* * public class ListNode { * int val; * ListNode next = null; * } */ public class Solution { /** * * @param head ListNode类 the head node * @return ListNode类 */ public ListNode sortInList (ListNode head) { // write code here PriorityQueue<ListNode> queue=new PriorityQueue<>((n1,n2)->n1.val-n2.val); while(head!=null){ queue.add(head); head=head.next; } ListNode pre=new ListNode(-1); ListNode cur=pre; while(!queue.isEmpty()){ ListNode tmp=queue.poll(); cur.next=tmp; cur=tmp; } cur.next = null; return pre.next; } }
自己实现的比较器,没有用collection的sort方法。但是不太明白为啥没有cur.next = null;这个不能通过,如果是用集合而不是队列来接收的话,这个指向为空是不需要的。
import java.util.*; /* * public class ListNode { * int val; * ListNode next = null; * } */ public class Solution { /** * * @param head ListNode类 the head node * @return ListNode类 */ public ListNode sortInList (ListNode head) { // write code here ArrayList<Integer> list=new ArrayList<>(); while(head!=null){ list.add(head.val); head=head.next; } Collections.sort(list); ListNode cur=new ListNode(-1); ListNode pre=cur; for(int c:list){ ListNode tmp=new ListNode(c); pre.next=tmp; pre=tmp; } return cur.next; } }不理解!!!