题解 | #单链表的排序#
单链表的排序
https://www.nowcoder.com/practice/f23604257af94d939848729b1a5cda08
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 List<Integer> list = new ArrayList<>(); while (head != null) { list.add(head.val); head = head.next; } Collections.sort(list); ListNode sortHead = new ListNode(0); ListNode cur = sortHead; for (int i = 0; i < list.size(); ++i) { cur.next = new ListNode(list.get(i)); cur = cur.next; } return sortHead.next; } }