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 sortLinkedList (ListNode head) {
        // write code here
        ArrayList<Integer> arrayList = new ArrayList<>();
        ListNode node = head;
        while (null != node) {
            arrayList.add(node.val);
            node = node.next;
        }
        int[] nums = arrayList.stream().mapToInt(Integer::intValue).toArray();
        quickSort(nums, 0, arrayList.size() - 1);
        node = head;
        for (int num : nums) {
            node.val = num;
            node = node.next;
        }
        return head;
    }
    
    public void quickSort(int[] nums, int start, int end) {
        
        if (start >= end) {
            return;
        }
        
        int l = start - 1;
        int r = end + 1;
        int p = start;
        int val = nums[end];
        while (p < r) {
            if (nums[p] < val) { // 小于
                int swap = nums[p];
                nums[p] = nums[l + 1];
                nums[l + 1] = swap;
                p++;
                l++;
            }
            else if (nums[p] > val) { // 大于
                int swap = nums[p];
                nums[p] = nums[r - 1];
                nums[r - 1] = swap;
                r--;
            }
            else {
                p++;
            }
        }
        quickSort(nums, start, l);
        quickSort(nums, r, end);
    }
}