0

The remove function for my singly linked chain does not work when I remove the very first node. Say I have {33,40,50} when I try and remove 33 i get a segfault, but the other two work fine. I think I just need some fresh eyes to see what i messed up in my remove function.

remove function

bool Set::remove(int X)
{
        bool Flag = false;
        Node * Prev = Head;
        Node * Curr = Head->Succ;
        //unsigned Z = 0;

        while(Curr->Item != X)
        {
                Prev = Curr;
                Curr = Curr->Succ;
        }
        Prev->Succ =Curr->Succ;
        delete Curr;
        Num--;
        Flag = true;
        return Flag;
}
4

5 回答 5

1

I think its because you start with Curr = Head->Succ which is already past 33(Curr->item is 40). You are also never checking to see if its at the end of the list. So you're accessing memory that is out of bounds.

于 2012-11-15T21:20:36.340 回答
1

You should check whether you went through the end of the list.

And you should start on the first element rather than the second (which, in this case, causes you to go through the list and try to continue further).

于 2012-11-15T21:21:03.073 回答
1

You are starting the search at the wrong place:

Change from:

    Node * Prev = Head;
    Node * Curr = Head->Succ;

to:

    Node * Prev = null;
    Node * Curr = Head;

But the real problem for segfault is that you haven't considered the scenario for a terminating condition if the specified element is not found in your linked list.

You might implement a terminating condition as follows:

bool Set::remove(int X)
{
        Node * Prev = Head;
        Node * Curr = Head->Succ;
        while(Curr->Item != X)
        {
                Prev = Curr;
                Curr = Curr->Succ;
                if ( null == Curr ) {
                    // If you've reached the end of your
                    // linked list and haven't found the item
                    // yet, give up looking and return
                    return false;
                }
        }
        Prev->Succ =Curr->Succ;
        delete Curr;
        Num--;
        return true;
}

Note: I also cleaned up your code a bit to remove bool Flag as it's unnecessary.

于 2012-11-15T21:21:49.943 回答
1

您的 Curr 变量从SECOND位置开始。Head 指向第一个位置,而 Curr 指向 head 指向两个的位置(这是第二个!)。这会产生无限循环并使程序崩溃。从这个开始currhead不是这个

于 2012-11-15T21:22:27.073 回答
0

Curr 被初始化:

Node * Curr = Head->Succ;

意思是当你做

while(Curr->Item != X)

您正在跳过“头”值。由于 Curr->Item 永远不会是 33(头值),因此您将继续使用 Succ,直到最终到达列表末尾的 NULL 指针。您没有在 while 中检查是否已到达列表末尾,因此在执行时会出现分段错误

Curr->Item != X
OR
Curr = Curr->Succ;

尝试初始化:

Node * Curr = Head;
于 2012-11-15T21:24:59.573 回答