链表排序(归并法)
2017-06-01 16:05
281 查看
1归并法
class ListNode { public: int val; ListNode *next; ListNode(int val) { this->val = val; this->next = NULL; } }
ListNode *sortList(ListNode *head) { if (head == nullptr || head->next == nullptr) return head; ListNode *mid = findMid(head); //找中点 ListNode *right = sortList(mid->next); mid->next = nullptr; //从中间断开 ListNode *left = sortList(head); return merge(left, right); } ListNode* findMid(ListNode* head) { ListNode *slow = head; ListNode *fast = head->next; while (fast && fast->next) { fast = fast->next->next; slow = slow->next; } return slow; } ListNode* merge(ListNode* head1, ListNode* head2) { ListNode dummy(-1); ListNode* tail = &dummy; while (head1 && head2) { if (head1->val < head2->val) { tail->next = head1; head1 = head1->next; } else { tail->next = head2; head2 = head2->next; } tail = tail->next; } if (head1) { tail->next = head1; } if (head2) { tail->next = head2; } return dummy.next; }
相关文章推荐
- 经典面试题:Java实现-归并K条已排序的链表及复杂度分析、优化
- C语言数据结构 链表与归并排序实例详解
- 链表的归并排序
- 链表排序(冒泡、选择、插入、快排、归并、希尔、堆排序)
- 链表实现归并(快速、插入)排序
- 链表排序--归并排序
- 【面经笔记】链表归并排序
- 链表的各种操作实现 链表逆序 链表排序 有序链表归并 链表存在环的判定
- 链表排序(冒泡、选择、插入、快排、归并)
- C/C++ 数组,链表排序(平均时间复杂度 O(nlogn))归并、快速、堆、希尔之归并排序
- 链表排序(冒泡、选择、插入、快排、归并、希尔、堆排序)
- 对链表进行归并排序
- 将两个已排序的链表归并成一个链表(C++面试题)
- 单链表排序(插入与归并)
- C语言中数据结构之链表归并排序实例代码
- 链表排序(冒泡、选择、插入、快排、归并、希尔、堆排序)【转载】
- 归并排序之数组和链表
- 单链表排序----快排 & 归并排序
- 链表排序(冒泡、选择、插入、快排、归并、希尔、堆排序)
- 单链表排序--归并排序