import java.util.*;
/*
* public class ListNode {
* int val;
* ListNode next = null;
* public ListNode(int val) {
* this.val = val;
* }
* }
*/
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param head ListNode类 the head node
* @return ListNode类
*/
public ListNode sortInList (ListNode head) {
// write code here
int arr[] = new int[size(head)];
ListNode p = head;
// 先将链表元素放到一个数组中
for(int i = 0; p != null; i++, p = p.next){
arr[i] = p.val;
}
// 对数组元素排序
Arrays.sort(arr);
head = new ListNode(arr[0]);
ListNode cur = head, newNode;
// 重新构建链表
for(int j = 1; j < arr.length; j++) {
newNode = new ListNode(arr[j]);
cur.next = newNode;
cur = newNode;
}
return head;
}
// 求链表长度
public int size(ListNode head) {
int cnt = 0;
ListNode p = head;
while(p != null) {
cnt++;
p = p.next;
}
return cnt;
}
}