public class Solution {
public ListNode insertionSortList(ListNode head) {
if (head == null) {
return null;
}
ListNode newHeadNode = new ListNode(head.val);
head = head.next;
while (head != null) {
ListNode insertNode = new ListNode(head.val);
ListNode prev = null;
ListNode cur = newHeadNode;
while (cur != null) {
if (insertNode.val < cur.val) {
if (prev == null) {
insertNode.next = cur;
newHeadNode = insertNode;
break;
}
else {
prev.next = insertNode;
insertNode.next = cur;
break;
}
}
else {
prev = cur;
cur = cur.next;
}
}
if (cur == null) {
prev.next = insertNode;
insertNode.next = null;
}
head = head.next;
}
return newHeadNode;
}
}
Sort a linked list using insertion sort.
Nothing much to explain. Just be careful when you insert this node at the beginning or at the end.