簡體   English   中英

C ++ STL pop_heap不起作用

[英]C++ STL pop_heap not work

我正在嘗試使用堆來解決問題“合並K列表”,它合並了k個已排序的鏈表並將其作為一個排序列表返回。 通常我創建一個min heap來存儲所有列表節點,並使用預定義函數LessThanLinkedList()進行比較。 但我發現第62行和第75行中的pop_heap()操作永遠不會起作用。 雖然我使用預定義的比較函數作為參數,但它不會刪除堆的頂部。 以下是我的代碼。 我使用visual studio 2010作為IDE。 誰知道原因? 非常感謝你的幫助!

#include <stdio.h>
#include <stdlib.h>
#include <vector>
#include <queue>
#include <list>
#include <numeric>

struct ListNode {
  int val;
  ListNode *next;
  ListNode(int x) : val(x), next(NULL) {}
};
using namespace std;

class Solution {
public:

  static bool LessThanLinkedList( const ListNode * l1, const ListNode * l2) 
  {
     return( l1->val > l2->val );
  }

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

     int idx;
     bool ball_list_null;
     ListNode * pNode;
     ListNode *new_head;

     ball_list_null = true;

     for( idx = 0; idx < lists.size(); idx++ )
     {
         if( NULL != lists[idx] )
         {
             ball_list_null = false;
             break;
         }
     }
     if( true == ball_list_null )
         return(NULL);

     vector< ListNode* > list_heap;
     for( idx = 0; idx < lists.size(); idx++ )
     {
         if( NULL != lists[idx] )
         {
             pNode = lists[idx];
             while( NULL != pNode )
             {
                 list_heap.push_back( pNode );
                 pNode = pNode->next;
             }
         }
     }

     make_heap( list_heap.begin(), list_heap.end(), LessThanLinkedList );

     if(list_heap.size() > 0) 
     {
         new_head = list_heap[0];
         pop_heap( list_heap.begin(), list_heap.end(), LessThanLinkedList );//not work
     }

     if( list_heap.size() == 0 )
     {
         new_head->next = NULL;
     }
     else
     {
         pNode = new_head;
         while( list_heap.size() >0 )
         {
             pNode->next = list_heap[0];
             pop_heap( list_heap.begin(), list_heap.end(), LessThanLinkedList ); // not work
             pNode = pNode->next ;
         }
         pNode->next = NULL;
     }
     return( new_head );

  }
};

void main()
{
  Solution xpfsln;
  ListNode *l1,*l2,*l3,*l4,*l5,*l6,*l7,*head;
  l1 = new ListNode(1);
  l2 = new ListNode(2);
  l3 = new ListNode(3);

  l1->next = l2;
  l2->next = l3;
  l3->next = NULL;

  vector<ListNode *> list_vec;
  list_vec.push_back(l1);

  head = xpfsln.mergeKLists( list_vec );
}

pop_heap不會從容器中刪除元素。 它不能,因為它甚至不能訪問容器,只是它的元素。 它的作用(當然假設[begin, end)形成一個有效的非空堆)重新排列元素,使得堆的第一個元素移動到該范圍的最后一個元素,並離開[begin, end-1)作為有效堆。 如果你想從容器中實際刪除元素,你只需要在調用pop_heap后擦除容器的最后一個元素(例如調用pop_back() )。

pop_heap( list_heap.begin(), list_heap.end(), LessThanLinkedList );
list_heap.pop_back();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM