gpt4 book ai didi

C++双向链表搜索和删除

转载 作者:太空宇宙 更新时间:2023-11-04 13:50:27 26 4
gpt4 key购买 nike

我在查找列表中的节点然后将其删除时遇到问题。我已经尝试了很多方法,但到目前为止这是我的代码。我不知道问题是在我的插件中还是在我的显示功能中?我几乎没学过这个。

void removeStudent(int id)
{
node *trash = NULL;

node *current = head;
while ( current!= NULL)
{
if ( current->data.id == id)
{
trash = current;
current->prev->next = current->next;
current->next->prev = current->prev;
delete trash;


}
}


}

这是我的插入函数

    void push(student s)
{

node *tmp = new node;
tmp->data = s;
tmp->next = head;
tmp->prev = NULL;

if (head == NULL)
{
head = tmp;
tail = tmp;
}
else
{
head->prev = tmp;
head = tmp;
}

}

这是我的显示功能

void display()
{
node *current = head;

while (current!=NULL)
{
cout << current->data.name << endl;
cout << current->data.GPA << endl;
cout << current->data.id << endl;
cout << current->data.university << endl;
current = current->next;
}
}

最佳答案

尝试以下操作。我想您的类还包含数据成员 tail。

void removeStudent( int id )
{
node *current = head;

while ( current != NULL && current->data.id != id ) current = current->next;

if ( current != NULL )
{
if ( current->prev != NULL ) current->prev->next = current->next;
else head = current->next;

if ( current->next != NULL ) current->next->prev = current->prev;
else tail = current->prev;

delete current;
}
}

如果你的类没有数据成员 tail 那么你必须删除语句

       else  tail = current->prev;

来自函数体。

关于C++双向链表搜索和删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23662984/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com