c - 删除所有大于特定值的数字
问题描述
我正在尝试执行一种算法来删除队列中大于特定值的所有数字,这是我的代码。
void problem(Queue* c, int x) {
if (isEmpty(c)) {
printf("empty queue");
} else {
Node* n1 = c->top;
Node* n2 = c->top->next;
while (n2 != NULL) {
if (n2->value > x) {
Nodo* aux = n2;
n1->next = aux->next;
aux->next = NULL;
free(aux);
}
n1 = n2;
n2 = n2->next;
}
}
}
解决方案
当if
条件为真时,就会出现问题。在这种情况下,您不想在该if
块之后继续使用n1 = n2;
,因为n2
现在是对已删除节点的引用。另一方面,您仍然需要移动n2
以指向下一个节点,因此这应该在当前节点被释放之前if
发生在块中。
这样做:
void problem(Queue* c, int x) {
if (isEmpty(c)) {
printf("empty queue");
} else {
Node* n1 = c->top;
Node* n2 = c->top->next;
while (n2 != NULL) {
if (n2->value > x) {
Node* aux = n2;
n2 = n2->next; // <-- add this; n1 remains unchanged.
n1->next = n2; // <-- now this can be shorter code
free(aux);
} else { // Make conditional
n1 = n2;
n2 = n2->next;
}
}
}
}
aux->next = NULL;
没有错,但也不需要,因为该节点已被释放。
推荐阅读
- xamarin - Xamarin form 4.3 Label using sans-serif front
- multithreading - Haskell 计算密集型线程阻塞所有其他线程
- olingo - Olingo OData 对 JSON 的响应
- sapui5 - SAPUI5 Fragment close 清除上一屏的数据
- asp.net-mvc - 是否可以使 GlobalConfiguration.Configure 异步?
- excel - 根据另一个工作表中的单元格值隐藏一个工作表中的行
- vb.net - 如何在控制台中输出选项卡?
- r - knitr:针织代码的更好再现性
- sql - Oracle - JSON_OBJECT - ORA-40478:输出值太大(最大值:4000)
- python-3.x - 如何在 Python 中从 statsmodels.tsa.x13 生成季节性分量预测?