Leetcode OJ : Merge k Sorted Lists 归并排序+最小堆 mergesort heap C++ solution
2015-02-18 12:56
375 查看
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ struct helper { ListNode *head; int len; helper(ListNode *h, int l) : head ( h ), len ( l ) {} }; class helpercmp { public: bool operator() (const helper &a, const helper &b) { return a.len > b.len; } }; class Solution { public: priority_queue<helper, vector<helper>, helpercmp> heap; inline int listSize(ListNode *head) { int len = 0; for ( ; head != nullptr; head = head->next, len++ ); return len; } ListNode *mergeKLists(vector<ListNode *> &lists) { if ( lists.empty() ) return nullptr; if ( lists.size() == 1 ) return lists[0]; ListNode *head = nullptr, *left = nullptr, *right = nullptr; for ( auto list : lists ) { heap.push( helper(list, listSize(list) ) ); } while ( heap.size() != 1 ) { left = heap.top().head; heap.pop(); right = heap.top().head; heap.pop(); head = mergeList( left, right ); heap.push( helper( head, listSize(head) ) ); } return heap.top().head; } ListNode *mergeList(ListNode *a, ListNode *b) { ListNode dummy(0); ListNode *tail = &dummy; while ( a != nullptr && b != nullptr ) { if ( a-> val <= b->val ) { tail->next = a; a = a->next; } else { tail->next = b; b = b->next; } tail = tail->next; } tail->next = a == nullptr ? b : a; return dummy.next; } };
相关文章推荐
- c++-merge k sorted lists heap的灵活应用
- LeetCode OJ:Merge k Sorted Lists
- LeetCode OJ - Merge k Sorted Lists
- LeetCode OJ 之 Merge k Sorted Lists(合并k个有序链表)
- [LeetCode] Merge Two Sorted Lists, Solution
- [Merge Sort] Merge Two Sorted Lists
- LeetCode 21 — Merge Two Sorted Lists(C++ Java Python)
- [LeetCode] 021. Merge Two Sorted Lists (Easy) (C++/Python)
- [C++]Merge Two Sorted Lists 归并两个排序的链表
- 【leetcode c++】21 Merge Two Sorted Lists
- LeetCode OJ:Merge k Sorted Lists(归并k个链表)
- [LeetCode 21] Merge Two Sorted Lists Solution
- Leetcode Merge k Sorted Lists 利用stl heap来实现
- LeetCode 之 Merge Two / k Sorted Lists — C/C++ 实现
- LeetCode Merge K Sorted Lists 问题和解答程序 C++ priority queue实现方法
- LeetCode OJ - Merge Sorted Array & Merge Two Sorted Lists
- [leetcode]Merge k Sorted Lists @ Python [基础知识: heap]
- LeetCode OJ 之 Merge Two Sorted Lists(合并两个有序的链表)
- LeetCode OJ:Merge Two Sorted Lists(合并两个链表)
- Merge Two Sorted Lists(C++)