思路:
首先排序可以使用集合将所有节点放入集合中,然后再根据每个节点值进行排序。这个可以很容易做到,不再赘述
其次就是直接在链表上排序,如何排序可以使用归并排序的方式,代码如下:
class Solution {public ListNode sortList(ListNode head) {if (head == null || head.next == null) {return head;}// 步骤1: 切分链表ListNode prev = null, slow = head, fast = head;while (fast != null && fast.next != null) {prev = slow;slow = slow.next;fast = fast.next.next;}prev.next = null; // 将链表切分为两部分// 步骤2: 递归排序ListNode l1 = sortList(head);ListNode l2 = sortList(slow);// 步骤3: 合并两个排序好的链表return merge(l1, l2);}// 合并两个排序好的链表private ListNode merge(ListNode l1, ListNode l2) {ListNode dummy = new ListNode(0);ListNode curr = dummy;while (l1 != null && l2 != null) {if (l1.val < l2.val) {curr.next = l1;l1 = l1.next;} else {curr.next = l2;l2 = l2.next;}curr = curr.next;}if (l1 != null) {curr.next = l1;} else if (l2 != null) {curr.next = l2;}return dummy.next;}
}