题解 | #单链表的排序#
单链表的排序
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 if(head == null){ return null; } //查找链表长度 ListNode cur = head; int length = 0; while(cur != null){ length++; cur = cur.next; } //将链表的值放入到数组中并进行排序 int[] arr = new int[length]; ListNode cur1 = head; for(int i = 0; i < arr.length; i++){ arr[i] = cur1.val; cur1 = cur1.next; } Arrays.sort(arr); //将数组的值再放入到聊表中 ListNode cur2 = head; for(int i = 0; i<arr.length; i++){ cur2.val = arr[i]; cur2 = cur2.next; } return head; } }