题目链接
法一
public ListNode insertionSortList(ListNode head) {
ListNode dummy = new ListNode();
ListNode pre, cur = head, disorder;
dummy.next = head;
while (cur != null && cur.next != null) {
if (cur.val <= cur.next.val) {
cur = cur.next;
continue;
}
pre = dummy;
while (pre.next.val < cur.next.val) {
pre = pre.next;
}
disorder = cur.next;
cur.next = disorder.next;
disorder.next = pre.next;
pre.next = disorder;
}
return dummy.next;
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
本地测试
lay.showTitle(147);
Solution147 sol147 = new Solution147();
int[] nums147 = new int[]{-1, 5, 3, 4, 0};
ListNode head147 = new ListNode();
head147 = listOpt.creatListByArray(head147, nums147);
listOpt.showList(head147);
ListNode sortHead147 = sol147.insertionSortList(head147.next);
listOpt.showNoHeadList(sortHead147);