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 sortCowsIV (ListNode head) {
        // write code here
        List<Integer> list = new ArrayList<>();
        while (head != null) {
            list.add(head.val);
            head = head.next;
        }
        list.sort(new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return o1 - o2;
            }
        });

        ListNode node = new ListNode(0);
        ListNode result = node;

        for (int i = 0; i < list.size(); i++) {
            node.next = new ListNode(list.get(i));
            node = node.next;
        }
        return result.next;
    }
}

本题考察的知识点是链表,所用编程语言是java。

我先将链表值加入集合中,然后进行排序,重建链表