Sort a linked list using insertion sort.
1. Create a new head and keep two pointer which are pre pointer and current pointer.
2. Each nodes need to be compared to the current node to find a node's value bigger than this node.
3. insert this node between pre and cur node.
易错点: 在插完之后, 必须要把pre 和 cur 指针 指到最前
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode insertionSortList(ListNode head) {
ListNode newHead = new ListNode(Integer.MIN_VALUE);
ListNode pre = newHead;
ListNode cur = newHead.next;
while(head != null){
while(cur != null && cur.val < head.val){
pre = cur;
cur = cur.next;
}
ListNode insertNode = head;
head = head.next;
pre.next = insertNode;
insertNode.next = cur;
pre = newHead;
cur = newHead.next;
}
return newHead.next;
}
}