Q:使用插入排序对链表进行排序。
A:
创建头结点;
public ListNode insertionSortList(ListNode head) {
if (head == null || head.next == null)
return head;
ListNode head0 = new ListNode(Integer.MIN_VALUE);
ListNode node1 = head;
ListNode node2 = head;
ListNode tempNode = head0;
boolean flag = false;
while (node1 != null) {
while (tempNode.next != null) {
if (tempNode.next.val > node1.val) {
flag = true;
node2 = node1.next;
node1.next = tempNode.next;
tempNode.next = node1;
tempNode = tempNode.next;
break;
}
tempNode = tempNode.next;
}
if(!flag){
node2 = node1.next;
node1.next = tempNode.next;
tempNode.next = node1;
}
flag = false;
tempNode = head0;
node1 = node2;
}
return head0.next;
}