题目描述
Sort a linked list using insertion sort.
public class Solution {
public ListNode insertionSortList(ListNode head) {
if (head==null) {
return head;
}
ListNode newHead = new ListNode(Integer.MIN_VALUE);
ListNode result = newHead;
ListNode curren = head;
while (curren!=null) {
// 保存下一个节点
ListNode next = curren.next;
newHead = result;
while (newHead.next!=null&&newHead.next.val<curren.val) {
newHead = newHead.next;
}
curren.next = newHead.next;
newHead.next = curren;
curren = next;
}
return result.next;
}
}