题解 | #单链表的排序#自建新链表,容易理解一些
单链表的排序
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) {
List<Integer> list = new ArrayList<>();
ListNode node = head;
while (true) {
list.add(node.val);
if (node.next == null) {
break;
}
node = node.next;
}
Collections.sort(list);
ListNode newNode = new ListNode(-1);
ListNode temp = newNode;
for (int num : list) {
temp.next = new ListNode(num);
temp = temp.next;
}
return newNode.next;
}
}

查看26道真题和解析