链表的归并排序与快速排序
2016-08-10 15:03
405 查看
链表数据结构
链表归并排序
基于值交换的链表快速排序
基于节点交换的链表快速排序
struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} };
链表归并排序
class Solution { public: ListNode* sortList(ListNode* head) { if (head == nullptr || head->next == nullptr) return head; ListNode *fast = head, *slow = head; while (fast->next && fast->next->next) { slow = slow->next; fast = fast->next->next; } fast = slow->next; slow->next = nullptr; head = sortList(head); fast = sortList(fast); return merge(head, fast); } private: ListNode* merge(ListNode *l1, ListNode *l2) { ListNode empty(-1); ListNode *tail = ∅ ListNode *tmp; for (; l1 || l2; tail = tail->next) { if (l1 == nullptr) { tail->next = l2; break; } if (l2 == nullptr) { tail->next = l1; break; } if (l1->val <= l2->val) { tmp = l1; l1 = l1->next; } else { tmp = l2; l2 = l2->next; } tail->next = tmp; } return empty.next; } };
基于值交换的链表快速排序
class Solution { public: ListNode* sortList(ListNode* head) { return sort(head, nullptr); } private: void swap(ListNode *a, ListNode *b) { int tmp = a->val; a->val = b->val; b->val = tmp; } ListNode *sort(ListNode *begin, ListNode *end) { if (begin == nullptr || begin == end || begin->next == end) return begin; int key = begin->val; ListNode *p = begin; ListNode *q = begin->next; for (; q != end; q = q->next) { if (q->val < key) { p = p->next; swap(p, q); } } swap(p, begin); sort(begin, p); sort(p->next, end); return begin; } };
基于节点交换的链表快速排序
class Solution { public: ListNode* sortList(ListNode* head) { return sort(head, nullptr); } private: ListNode *sort(ListNode *begin, ListNode *end) { if (begin == nullptr || begin == end || begin->next == end) return begin; ListNode *part = patition(begin, end); ListNode *first = sort(begin, part); ListNode *second = sort(part->next, end); part->next = second; return first; } ListNode *patition(ListNode * &begin, ListNode *end) { ListNode *head = begin; ListNode *tail = begin; ListNode *cur = begin->next; while (cur != end) { if (cur->val < begin->val) { tail->next = cur->next; cur->next = head; head = cur; cur = tail; } tail = cur; cur = cur->next; } ListNode *part = begin; begin = head; return part; } };
相关文章推荐
- LintCode刷题链表排序——归并和快速排序
- 【数据结构】 MergeSort与QuickSort的详细分析 - 归并排序、快速排序
- 将两个已排序的链表归并成一个链表(C++面试题)
- 单链表排序--归并排序
- 链表排序--归并排序
- 数据结构之排序大集合(下)(选择、堆、基数、归并,链表排序)
- 148 Sort List (归并实现链表排序)
- 链表排序(冒泡、选择、插入、快排、归并、希尔、堆排序)
- 单向链表归并排序
- 单链表的归并、快速排序 C++
- 堆排序、快速排序(递归与非递归)、归并排序效率比较
- 数据结构之排序大集合(下)(选择、堆、基数、归并,链表排序)
- 简单排序Java实现(二):归并排序,快速排序
- 常见排序算法整理(三)----归并排序、快速排序
- 链表的各种操作实现 链表逆序 链表排序 有序链表归并 链表存在环的判定
- 归并排序和快速排序
- 链表的归并排序
- Algs4-2.2.17链表归并排序
- C语言中数据结构之链表归并排序实例代码
- 链表排序(归并法)