删除链表中的最小节点

时间:2014-10-13 18:08:15

标签: pointers linked-list

我尝试编写以下函数来删除链表中的最小节点。但是,我收到错误,我无法纠正它。请帮忙。

错误是 - >错误1错误C4703:可能未初始化的本地指针变量'trailSmall'使用

这是我的代码:

void linkedListType<T>::deleteSmallest()
{
nodeType<T> *current;
nodeType<T> *trailCurrent;     // used for pointing to node just before current

nodeType<T> *small;
nodeType<T> *trailSmall;     

if (first == NULL)
    cout << "Cannot delete from an empty list." << endl;
else
    if (first->link == NULL)
    {
        first = NULL;
        delete last;
        last = NULL;
    }
    else
    {
        small = first;
        trailCurrent = first;
        current = first->link;

        while (current != NULL)
        {
            if (small->info > current->info)
            {
                trailSmall = trailCurrent;
                small = current;
            }

            trailCurrent = current;
            current = current->link;
        }

        if (small == first)
            first = first->link;
        else if (small != first)
        {
            trailSmall->link = small->link;

            if (small == last)
                last = trailSmall;
        }

        delete small;
    }
}

1 个答案:

答案 0 :(得分:0)

错误消息(异常)非常明确:您的代码可能会显示trialSmall,但并不总是将其设置为任何内容。但我认为你很安全;访问trialSmall的唯一时间是,如果你得到了非平凡的情况,那么small != first(你不需要明确地测试,因为你刚刚确定small==first 1}}不是真的);但是small更改的位置是trialSmall更改的位置。 (对于编译器来说,这是一个非常微妙的事情。)

我要继续将trialSmall初始化为first以安抚编译器。