Insertion Sort List

描述

Sort a linked list using insertion sort.

分析

代码

  1. // Insertion Sort List
  2. // 时间复杂度O(n^2),空间复杂度O(1)
  3. public class Solution {
  4. public ListNode insertionSortList(ListNode head) {
  5. ListNode dummy = new ListNode(Integer.MIN_VALUE);
  6. //dummy.next = head;
  7. for (ListNode cur = head; cur != null;) {
  8. ListNode pos = findInsertPos(dummy, cur.val);
  9. ListNode tmp = cur.next;
  10. cur.next = pos.next;
  11. pos.next = cur;
  12. cur = tmp;
  13. }
  14. return dummy.next;
  15. }
  16. ListNode findInsertPos(ListNode head, int x) {
  17. ListNode pre = null;
  18. for (ListNode cur = head; cur != null && cur.val <= x;
  19. pre = cur, cur = cur.next)
  20. ;
  21. return pre;
  22. }
  23. }

相关题目

原文: https://soulmachine.gitbooks.io/algorithm-essentials/content/java/sorting/insertion-sort/insertion-sort-list.html