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 29 30 31 32 33 34
| class Solution { public ListNode insertionSortList(ListNode head) { if (head == null || head.next == null) { return head; } ListNode ans = new ListNode(0); ListNode p = head; while (p != null) { insert(ans, new ListNode(p.val)); p = p.next; } return ans.next; }
private void insert(ListNode list, ListNode node) { if (list.next == null) { list.next = node; return; }
ListNode pre = list; ListNode p = list.next; while (p != null) { if (node.val < p.val) { pre.next = node; node.next = p; return; } pre = pre.next; p = p.next; } pre.next = node; } }
|