C++ 双链接列表插入和显示以及搜索和删除
我正在实现一个双链接列表,我的搜索和删除函数给了我一个错误。 我是新的双链接列表,所以任何帮助将不胜感激 这是我的插入函数C++ 双链接列表插入和显示以及搜索和删除,c++,C++,我正在实现一个双链接列表,我的搜索和删除函数给了我一个错误。 我是新的双链接列表,所以任何帮助将不胜感激 这是我的插入函数 void push(student s) { if ( head == NULL) { node *tmp = new node; tmp->data = s; tmp->next = NULL; tmp->prev = NULL; head = tmp; t
void push(student s)
{
if ( head == NULL)
{
node *tmp = new node;
tmp->data = s;
tmp->next = NULL;
tmp->prev = NULL;
head = tmp;
tail = tmp;
}
else if ( head != NULL)
{
node *tmp = new node;
tmp->data = s;
tmp->next = head;
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;
}
}
这是我的主要任务
int main()
{
student me;
student you;
you.id = 9;
you.GPA = 9.8;
you.name = "peter";
you.university = "stc";
me.id = 20;
me.GPA = 20.0;
me.name = "robert";
me.university = "utpa";
student mee;
mee.id = 15;
mee.GPA = 8.9;
mee.name = "mike";
mee.university = "utpa";
studentList list;
list.push(me);
list.push(you);
list.push(mee);
list.pop();
list.removeStudent(15);
list.display();
return 0;
}
检查head
是否为NULL
,如果为空,则分配head
。然后检查head
是否不是NULL
,此时它肯定不是上面指定的值,然后执行其他操作
简单的解决方案是,将两个if
结构更改为if
…else if
,例如
if ( head == NULL)
{
...
head = tmp;
}
else if ( head != NULL)
{
...
head = tmp;
}
问题在于您的
push
功能。您可以大大简化它以避免条件逻辑问题:
void push(student s)
{
node *tmp = new node;
tmp->data = s;
tmp->next = head; // this works even when head is NULL
tmp->prev = NULL;
if (head == NULL)
{
head = tmp;
tail = tmp;
}
else
{
head->prev = tmp;
head = tmp;
}
}
即使这比它需要的要复杂一点——如果
if
条件head==NULL
失败,那么head
不能为NULL。瞧,没有必要测试head!=空
,只需单独使用else
。请参阅我对Zac答案的评论——如果是多余的,则您的第二个。不清楚推
应该在前面还是后面推,您能澄清一下吗?
if ( head == NULL)
{
...
head = tmp;
}
else if ( head != NULL)
{
...
head = tmp;
}
void push(student s)
{
node *tmp = new node;
tmp->data = s;
tmp->next = head; // this works even when head is NULL
tmp->prev = NULL;
if (head == NULL)
{
head = tmp;
tail = tmp;
}
else
{
head->prev = tmp;
head = tmp;
}
}