C ++链表:不会删除第一个输入

时间:2019-11-09 12:32:05

标签: c++

我想问一下为什么删除功能在第一个输入上不起作用,但是在其他输入(例如第二个上,等等)上却起作用了。非常感谢您的帮助!

void deleteStudent(){
cout<<endl;
cout<<"~DELETING A STUDENT~"<<endl;
cout<<endl;

string deletion;
cout << "Enter student ID number: ";
cin >> deletion;

student *prev = head;
student *current = head->next;

while (current)
{
    if (current->studentNum == deletion){
        prev->next = current->next;
        delete current;
        return;
    }
    prev = current;
    current = current->next;
}
if (!current){
    cout << "That value is not in the list" << endl;
}

}

3 个答案:

答案 0 :(得分:1)

您使用的是我所说的不好的Java方法。

例如,一开始的代码会调用未定义的行为

student *prev = head;
student *current = head->next;

因为一般的头可能等于nullptr

而且head可以是应该删除的节点。但是,您正在跳过它。

此代码段

student *prev = head;
student *current = head->next;

while (current)
{
    if (current->studentNum == deletion){
        prev->next = current->next;
        delete current;
        return;
    }
    prev = current;
    current = current->next;
}
if (!current){
    cout << "That value is not in the list" << endl;
}

可以通过以下方式重写

student **current = &head;

while ( *current != nullptr && ( *current )->studentNum != deletion )
{
    current = &( *current )->next;
}

if ( *current != nullptr )
{
    student *tmp = *current;
    *current = ( *current )->next;
    delete tmp;
}
else
{
    cout << "That value is not in the list" << endl;
}

答案 1 :(得分:0)

这行是错误的。

student *current = head->next;

请在下面查看我的更正。

void deleteStudent(){
cout<<endl;
cout<<"~DELETING A STUDENT~"<<endl;
cout<<endl;

string deletion;
cout << "Enter student ID number: ";
cin >> deletion;

student *prev = head;
student *current = head;

while (current)
{
    if (current->studentNum == deletion){
        if(current == head)
           head = prev;
        prev->next = current->next;
        delete current;
        return;
    }
    prev = current;
    current = current->next;
}
if (!current){
    cout << "That value is not in the list" << endl;
}
} 

答案 2 :(得分:0)

由于这似乎是一种分配问题,所以我告诉您您哪里出错了,

从您的代码中, 似乎变量“ head”是您的第一个节点。 而电流对应第二个节点。

while (current)
{
    if (current->studentNum == deletion){
        prev->next = current->next;
        delete current;
        return;
    }
    prev = current;
    current = current->next;
}
在上面的代码中,

基本上是从第二个节点迭代到列表的末尾。这就是为什么您不能删除第一个节点的原因。

将while循环中的条件从当前更改为prev。 并注意删除第一个节点基本上就是删除指向整个列表的指针,并且可能导致不必要的行为,可以通过使用检查条件是否要删除第一个节点来避免这种情况,如果这样,则更新与列表相对应的指针相应地。