Insertion Sort List

描述

Sort a linked list using insertion sort.

分析

代码

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

相关题目

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