我正在尝试编写一种方法,该方法获取链接列表(** pplist)和要删除的项目的地址(* pplaneToDelete)。 这是我写的,程序崩溃了。有帮助吗?
void DeleteAirplane(plane **pplist, plane *pplaneToDelete) {
plane *cur = pplist, *prev = NULL;
if (cur = pplaneToDelete) {
pplist =cur->next_plane;
free(cur);
}
while ((cur != pplaneToDelete) && (cur != NULL)) {
prev = cur;
cur = cur->next_plane;
}
if (cur != NULL) {
prev->next_plane = cur->next_plane;
free(cur);
}
}
修改: 我更改为:
void DeleteAirplane(plane **pplist, plane *pplaneToDelete) {
plane *cur = *pplist, *prev = NULL;
if (cur == pplaneToDelete) {
*pplist =cur->next_plane;
free(cur);
return;
}
while ((cur != pplaneToDelete) && (cur != NULL)) {
prev = cur;
cur = cur->next_plane;
}
if (cur != NULL) {
prev->next_plane = cur->next_plane;
free(cur);
}
}
有效! 任何意见?
答案 0 :(得分:1)
这里没有什么问题。
(cur = pplaneToDelete)
是分配而不是比较
因此将其更改为(cur == pplaneToDelete)
。
pplist
是指向指针的指针,因此您需要取消引用它才能获取其持有的指针对象。
plane *cur = pplist
-> plane *cur = *pplist
pplist =cur->next_plane;
---> *pplist =cur->next_plane;
删除头节点后,您需要return
,否则将尝试访问cur
指针来调用未定义的行为。
if (cur == pplaneToDelete) {
*pplist =cur->next_plane;
free(cur);
return; // Node deleted now return.
}