import java.util.*;

/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 *   public ListNode(int val) {
 *     this.val = val;
 *   }
 * }
 */

public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param head ListNode类 
     * @return ListNode类
     */
    public ListNode sortList (ListNode head) {
        // write code here
        ListNode hair = new ListNode(0), p, cur = head, next;
        while (cur != null) {
            next = cur.next;
            p = hair;
            while (p.next != null && p.next.val < cur.val) p = p.next;
            cur.next = p.next;
            p.next = cur;
            cur = next;
        }
        return hair.next;
    }
}
  • 定义一个虚拟头节点 hair 和指向 hair 的 p,以及指向原链表 head 的 cur
  • 基于 cur 遍历原链表,每次用 p 在 hair 链表中找到值小于当前cur指向节点的值的前一个节点,然后将 cur 指向节点插入到hair链表中
  • 最后返回 hair.next