动态分配列表 - 创建一个函数,用于删除所有包含偶数值的元素

Dynamic allocated lists - create a function that deletes all the elements which contain an even value

本文关键字:删除 用于 包含偶 元素 函数 创建 列表 一个 动态分配      更新时间:2023-10-16

正如我的作业,我必须创建一个程序来删除所有包含偶数值的节点。

以下是我的做法:

#include <iostream>
using namespace std;
struct node {
int info;
node* next;
};
void sterge(node*& p)
{
node* t;
t = new node;
if (p->info % 2 == 0)
{
p = p->next;
}
t = p;
while (t != NULL)
{
if (t->next != NULL)
{
if (t->next->info % 2 == 0)
{
node* aux;
aux = t->next;
t->next = t->next->next;
delete aux;
}
}
t = t->next;
}
}
int main()
{
node* head = new node;
head->info = 5;
node* p = new node;
node* t = new node;
t->info = 2;
head->next = t;
p = head;
node* x = new node;
x->info = 4;
node* w = new node;
w->info = 6;
t->next = x;
x->next = w;
w->next = nullptr;
sterge(head);
//Loop through the list and print each value
while (p != NULL) {
cout << p->info << endl;
p = p->next;
}
return 0;
}

但是在 main 中创建的节点的输出是 5 和 4。 我知道原因,但我不知道如何解决。

基本上,我验证下一个节点是否具有偶数值,然后转到下一个节点。所以它看起来像这样:

5 -> 下一个是偶数,所以 2 被删除 ->转到下一个节点,即 4

^现在的问题是这个节点没有被检查,因为我总是检查下一个节点。因此,程序认为它是有效的。

那么如何修复我的程序呢?

delete后加上一个continue

这样,下一次迭代将立即开始,而不执行当前迭代的其余部分,因此将跳过不需要的t = t->next