从单个链接列表中删除整个节点

时间:2011-05-28 11:52:41

标签: c++ linked-list

我试过了,但我无法让它发挥作用。我需要从链表中删除元素 number 。这是我到目前为止所做的:

class MatrixLL
{
private:
    struct MatrixLLElem
    {
        Matrix elem;
        MatrixLLElem* next;
        MatrixLLElem(const Matrix& m1): elem(m1), next(NULL)
        { }
    };
    MatrixLLElem* start;
public:
    MatrixLL();
    Matrix& elem(const int index);
    int getlength();
    void append(const Matrix& m1);
    void deleteelem(const int index);
    ~MatrixLL();
};

我的其他代码无关紧要,因为它完美运行,所以这里是deleteelem()的代码;功能:

void MatrixLL::deleteelem(const int index)
{
    if(index < 1)
        throw "Invalid index specified.";

    if(start == NULL)
        throw "No element at specified location.";

    MatrixLLElem* currP = start;
    MatrixLLElem** prevP = NULL;

    for(int i = 1; i < index; i++)
    {
        prevP = &currP;
        if((*currP).next != NULL)
            currP = (*currP).next;
        else
            throw "No element at specified location.";
    }
    if(prevP == NULL)
    {
        start = NULL;
    }
    else
    {
        (*prevP) = (*currP).next;
    }
    delete currP;
}

编辑:如果我检查,它会将长度从2减少到0 ...如果我追加然后检查等长度函数似乎工作正常。索引应该从1开始。

4 个答案:

答案 0 :(得分:2)

问题是当你想删除第一个元素(index = 1)时。

而不是

start = NULL; // wrong

正确的是:

start = (*currP).next; // the second element now becomes the first element

答案 1 :(得分:1)

我做对了。如果它对某人有帮助,那就是代码:

void MatrixLL::deleteelem(const int index)
    {
    if(index < 1)
        throw "Invalid index specified.";

    if(start == NULL)
        throw "No element at specified location.";

    MatrixLLElem* currP = start;
    MatrixLLElem* prevP = NULL;

    for(int i = 1; i < index; i++)
    {
        prevP = currP;
        if((*currP).next != NULL)
            currP = (*currP).next;
        else
            throw "No element at specified location.";
    }

    if(prevP != NULL)
    {
        (*prevP).next = (*currP).next;
    }
    else
    {
        start = (*start).next;
    }

    delete currP;
}

仅供参考,起始索引为1,而不是0。

答案 2 :(得分:0)

(*prevP) = (*currP).next;

应该是

(*prevP).next = (*currP).next;

答案 3 :(得分:0)

看起来条件和更改指针部分是错误的。 应该是这样的:

MatrixLLElem* prevP = NULL; // Why ** ?

for(int i = 1; i <= index; ++i) // Here
{
    prevP = currP;
    if((*currP).next != NULL)
        currP = (*currP).next;
    else
        throw "No element at specified location.";
}
if(currP == start) // This would be better
{
    start = NULL;
}
else
{
    (*prevP).next = (*currP).next; // And here
}
delete currP;