题解 | #单链表的排序#
单链表的排序
http://www.nowcoder.com/practice/f23604257af94d939848729b1a5cda08
import java.util.*;
/*
* public class ListNode {
* int val;
* ListNode next = null;
* }
*/
public class Solution {
/**
*
* @param head ListNode类 the head node
* @return ListNode类
*/
public ListNode sortInList (ListNode head) {
// write code here
List<Integer> list = new ArrayList<>();
while(head != null){
list.add(head.val);
head = head.next;
}
Collections.sort(list);
ListNode pHead = new ListNode(-1);
ListNode res = pHead;
for(int i=0; i<list.size(); i++){
pHead.next = new ListNode(list.get(i));
pHead = pHead.next;
}
return res.next;
}
// public static int[] sort(int[] arr) {
// for(int i=0; i<arr.length; i++){
// for(int j=0; j<arr.length-i-1; j++){
// if(arr[i] > arr[j]){
// int tmp = arr[i];
// arr[i] = arr[j];
// arr[j] = tmp;
// }
// }
// }
// return arr;
// }
}