使用C ++删除范围为x1和x2的值的节点

时间:2017-12-28 08:07:07

标签: c++

我正在尝试实现一个删除范围内值的节点的函数DeleteNodes(T & val1, T & val2)。运行程序时发生未处理的异常错误。我无法弄清楚我在实施中做错了什么。我正在使用一个名为DeleteNode(T &val)的已定义函数来删除所需的节点。有人可以帮我解决这个问题吗?

void DLList<T>::DeleteNodes(T & val1 ,T & val2)
{
    if(IsEmpty())
        return;
    if(head == tail)
    {
        if(head->val >= val1 && head->val <= val2)
            DeleteHead();
    }

    DLLNode <T> *p;

    for(p = head ; p != NULL ; p  = p->next)
    {
        if(p->val >= val1 && p->val <= val2)
        {   T x = p->val;  
            DeleteNode(x);
        }   
    }
}

1 个答案:

答案 0 :(得分:0)

抱歉,这是我第一次提出这种类型的问题,我必须更具体一点,对于DeleteNode(T&amp; val)函数,它只删除一个所需节点,用于DeleteNodes( T&amp; val1,T&amp; val2)函数删除val1和val2之间范围内值的所有节点,这里是DeleteNode()函数:

bool DLList<T>::DeleteNode(T& val) 
{
bool found = false;

if(IsEmpty() == true)
    return false;

if(val == head->val)
{
    DeleteHead();
    return true;
}

if(val == tail->val)
{
    DeleteTail();
    return true;
}

DLLNode<T> *node, *predNode, *succNode;
node = predNode = succNode = NULL;

//Traverse list to find the node to be deleted
for(node = head->next; node != NULL; node = node->next)
{
    if(node->val == val)
    {
        found = true;
        break;
    }
}
if(found == true)
{
    // Unlink deleted node from list
    predNode = node->prev;
    succNode = node->next;
    predNode->next = node->next; 
    succNode->prev = node->prev;
    delete node;
}
return found;
}