Leetcode OJ : Merge k Sorted Lists 归并排序+最小堆 mergesort heap C++ solution

 1 /**

 2  * Definition for singly-linked list.

 3  * struct ListNode {

 4  *     int val;

 5  *     ListNode *next;

 6  *     ListNode(int x) : val(x), next(NULL) {}

 7  * };

 8  */

 9 

10 struct helper {

11     ListNode *head;

12     int len;

13     helper(ListNode *h, int l) : head ( h ), len ( l ) {}

14 };

15 

16 class helpercmp {

17 public:

18     bool operator() (const helper &a, const helper &b) {

19         return a.len > b.len;

20     }

21 };

22 

23 class Solution {

24 public:

25     priority_queue<helper, vector<helper>, helpercmp> heap; 

26     

27     inline int listSize(ListNode *head) {

28         int len = 0;

29         for ( ; head != nullptr; head = head->next, len++ );

30         return len;

31     }

32     ListNode *mergeKLists(vector<ListNode *> &lists) {

33         if ( lists.empty() ) return nullptr;

34         if ( lists.size() == 1 ) return lists[0];

35         ListNode *head = nullptr, *left = nullptr,  *right = nullptr;

36         for ( auto list : lists ) {

37             heap.push( helper(list, listSize(list) )  );

38         }

39         while ( heap.size() != 1 ) {

40             left = heap.top().head;

41             heap.pop();

42             right = heap.top().head;

43             heap.pop();

44             head = mergeList( left, right );

45             heap.push( helper( head, listSize(head) ) );

46         }

47         return heap.top().head;

48     }

49     ListNode *mergeList(ListNode *a, ListNode *b) {

50         ListNode dummy(0);

51         ListNode *tail = &dummy;

52         while ( a != nullptr && b != nullptr ) {

53             if ( a-> val <= b->val ) {

54                 tail->next = a;

55                 a = a->next;

56             } else {

57                 tail->next = b;

58                 b = b->next;

59             }

60             tail = tail->next;

61         }

62         tail->next =  a == nullptr ? b : a;

63         return dummy.next;

64     }

65 };

 

你可能感兴趣的:(mergesort)