0

我已经实现了removeSelection一个从左派堆中删除特定节点的函数。该代码通过一个哈希表定位节点,该哈希表跟踪已插入堆中的键。然后该节点被渗透到堆的根deleteMin并被调用以删除它。代码似乎在调用的swapWithParent函数中失败了percolateUp,它会产生一个段错误。

这是要从堆上的 main 调用的函数:

    bool removeSelection( const Comparable & x )
{
    LeftistNode * temp = locateNode( x ); //find the node with the item
    if(temp == NULL)
        return false;
    //percolate that node to the top
    percolateUp(temp);
    //delete the root
    int derp = 0; //deleteMin requires an int be passed
    deleteMin(derp);
    return true;

}

percolateUp功能:

    void percolateUp( LeftistNode * t )
{
    if(t != NULL)
    {
        while(t != root)
        {
            t = swapWithParent(t->parent, t);
        }
    }
}

swapWithParent功能:

    //swap h2 with its parent h1
//return pointer to h2's new location
LeftistNode * swapWithParent(LeftistNode * h1, LeftistNode * h2)
{
    //if h2 is its parent's left child
    if(h2 == h1->left)
    {
        LeftistNode *temp = new LeftistNode(h2->element, -1, h1->parent, h1->left, h1->right, h1->npl); //clone h1 and store as a temp

        temp->lines = h2->lines;

        //update all pointers
        h1->parent = h2;
        if(h1->right != NULL)
            h1->right->parent = h2;
        h1->left = h2->left;
        h1->right = h2->right;
        h2 = temp;
        return h2;
    }
    else
    {
        LeftistNode *temp = new LeftistNode(h2->element, -1, h1->parent, h1->left, h1->right, h1->npl); //clone h1 and store as a temp
        temp->lines = h2->lines;
        //update all pointers
        h1->parent = h2;
        if(h1->left != NULL)
            h1->left->parent = h2;
        h1->left = h2->left;
        h1->right = h2->right;
        h2 = temp;
        return h2;

    }
}

是否有任何地方我可能会取消引用 NULL 指针?我已经检查过了,但我似乎找不到错误。

4

1 回答 1

0

如果t->parent在调用中为 NULL,t = swapWithParent(t->parent, t);那么您将在swapWithParent(). 如果parent允许为 NULL,则在 swapWithParent() 中添加一个检查,如果它不应该为 NULL,则至少添加一个assert()以确保它不会被错误地设置为 NULL。

于 2012-03-28T05:02:47.313 回答