
一:归并实现
1.递归写法
2.非递归写法,数组模拟递归(STL里源码思路)
二:插入实现
归并递归写法:
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 35
|
class { public: ListNode* merge(ListNode* left, ListNode* right) { ListNode* result = new ListNode(-1); ListNode* r = result; while (left != NULL && right != NULL) { if (left->val <= right->val) { r->next = left; r = r->next; left = left->next; } else { r->next = right; r = r->next; right = right->next; } } if (left != NULL) r->next = left; if (right != NULL) r->next = right; return result->next; } ListNode* sortList(ListNode* head) { if (head == NULL || head ->next == NULL) return head; ListNode* pre = NULL; ListNode* fast = head, *slow = head; while (fast != NULL && fast->next != NULL) { pre = slow; fast = fast->next->next; slow = slow->next; } pre->next = NULL; ListNode* left = sortList(head); ListNode* right = sortList(slow); return merge(left, right); } };
|
归并非递归写法:
第二种着实很难理解,模拟了很久。敬畏敬畏。大道至简,就是这样哇。
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 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
|
class { public: ListNode* merge(ListNode* l1, ListNode* l2) { ListNode* result = new ListNode(-1); ListNode* r = result; while (l1 && l2) { if (l1->val <= l2->val) { r->next = l1; r = r->next; l1 = l1->next; } else { r->next = l2; r = r->next; l2 = l2->next; } } if (l1) { r->next = l1; } if (l2) { r->next = l2; } return result->next; } ListNode* table[64] = {NULL}; int fill = 0; int i = 0; ListNode* carry; ListNode* sortList(ListNode* head) { if (head == NULL || head->next == NULL) return head; while (head != NULL) { ListNode* next = head->next; head->next = carry; carry = head; i = 0; while (i < fill && table[i]) { table[i] = merge(carry, table[i]); carry = NULL; swap(carry, table[i++]); } swap(carry, table[i]); if(i == fill) fill++; head = next; } ListNode* result; for (int i = 1; i < fill; i++) { table[i] = merge(table[i], table[i-1]); } return table[fill-1]; } };
|
插入排序:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
|
class { public: ListNode* insertionSortList(ListNode* head) { ListNode* result = new ListNode(INT_MIN); ListNode* r = result; ListNode* next; while (head != NULL) { next = head->next; ListNode* r = result; while (r != NULL && r->next != NULL && r->next->val < head->val) { r = r->next; } head->next = r->next; r->next = head; head = next; } return result->next; } };
|
近期评论