问题描述(原题链接)
给你链表的头结点 head ,请将其按 升序 排列并返回 排序后的链表 。
代码:
/**
* 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)
return null;
ListNode temp = new ListNode(-1);
temp.next=head;
ListNode point =head.next; //待插入元素
ListNode sort = head; //已排序元素
while(point!=null){
if(sort.val<=point.val){
sort=sort.next;
}else{
ListNode search = temp;
while(search.next.val<=point.val){
search=search.next;
}
sort.next = point.next;
point.next=search.next;
search.next=point;
}
point=sort.next;
}
return temp.next;
}
}