簡體   English   中英

C ++霍夫曼樹和指針

[英]C++ Huffman Tree and Pointers

我正在創建一個霍夫曼樹,為此我開始制作一個Min Heap。 堆已設置並按文檔中的頻率對值進行排序,但是當我嘗試開始創建樹時出現問題。

我正在從堆中彈出前兩個項目並在它們上面放置一個節點並重新插入堆中。 堆是基於數組的,因此它不會觸及節點的* left和* right指針。 當堆只有一個節點時,它的左右節點指針都是空的,所以我相信它可能是我指針的問題......? 我是java新手,因為我犯了愚蠢的錯誤。

 while(theHeap.getheapSize() > 1)
    {
        Node top;
        Node *min1=new Node(theHeap.topandPop());
        Node *min2=new Node(theHeap.topandPop());
        top.left=min1;
        top.right=min2;
        top.freq=min1->freq+min2->freq;
        theHeap.insert(top);
    }
    Node r=theHeap.topAndPop(); //null pointers for left and right children

--------------------------------------
    //code for heap.  arr is in the header file is Node *arr;

void Heap::insert(Node c)
{
    if (heapSize != arrSize)
    {
        heapSize=heapSize+1;
        arr[heapSize - 1] = c; //does this call copy constructor???
        percolateUp(heapSize - 1);
    }
}
void Heap::percolateUp(int nodeIndex) {

    int parentIndex;
    Node tmp;
    if (nodeIndex != 0)
    {
        parentIndex = getParentPos(nodeIndex);
        if (arr[parentIndex].freq > arr[nodeIndex].freq)
        {
            tmp = arr[parentIndex];
            arr[parentIndex] = arr[nodeIndex];
            arr[nodeIndex] = tmp;
            percolateUp(parentIndex);

        }
    }
}

首先,我建議不要混合實例和指針,如果你選擇一個,你的任務就會簡單得多。 在這種情況下,我認為將指針存儲在堆中的節點而不是實例是合適的,額外的好處是指針的行為更像你習慣於Java,不需要擔心復制構造和賦值。 你只需要記住刪除它們(與Java不同),可以在堆的dtor中完成。

其次,回答代碼注釋中的問題:不會在Heap :: insert()中調用copy ctor,而是調用賦值運算符。 這是否是一個問題取決於Node類的外觀。

暫無
暫無

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

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