1.题目


2.思路
(1)计算节点数
(2)创建数组存储链表的节点值
(3)对数组进行排序
(4)利用尾插法生成链表



3.代码实现
java
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode sortList(ListNode head) {
//如果是空链表或者只有一个链表节点,我们直接返回
if(head==null||head.next==null)
{
return head;
}
int num=0;
ListNode tmp=head;
while(tmp!=null)
{
num++;
tmp=tmp.next;
}
//创建1个新数组
int[] nums=new int[num];
int i=0;
tmp=head;
while(tmp!=null)
{
nums[i]=tmp.val;
tmp=tmp.next;
i++;
}
//对数组进行排序
Arrays.sort(nums);
//因为nums是升序排序,所以构造链表是尾插法
//链表的头指针(第一个节点)。最终返回它。
ListNode begin=null;
ListNode end=null;
for(int j=0;j<num;j++)
{
if(begin==null)
{
begin=new ListNode(nums[j]);// 创建第一个节点
end=begin;// 此时头节点也是尾节点
}
else{
ListNode p=new ListNode(nums[j]);// // 新节点
end.next=p;// 把新节点接在"尾巴"后面
p.next=null;// 新节点的 next 指向 null
end=p;// 更新尾指针,指向新的尾节点
}
}
return begin;
}
}