所以我有这个结构
:
struct Book {
char *title;
char *author;
int pages;
struct Book *next;
}*start=NULL;
我有以下用于删除的功能:
void delete(int x) {
struct Book *current;
for(current = start; current; current = current->next) {
if(current->pages == x) {
current = current->next;
break;
}
}
}
出于某种原因,这不起作用。我做错了什么?
最佳答案
首先了解从链表中删除节点的逻辑。
假设你有一个链接列表 x1->x2->x3->x4 并且你想从中删除 x3。所以要删除x3,你所要做的就是让x2的next
指针指向x4。但在你这样做之前,你应该释放分配给节点 x3 的内存。
下面是实现这个的简单代码:
void delete(int x) {
struct Book *current;
for(current = start; current; current = current->next) {
if(current->next != NULL){
if(current->next->pages == x) {
Struct Book * temp = current->next; //save the address of the node to be deleted
current->next = current->next->next; //remove the node from the linked list
free(temp->author);
free(...); //whatever memory you want to release
free(temp); //free the memory
break;
}
}
}
}
上面的实现不包括要删除的节点是链表的头节点或根节点的情况。
void delete(int x) {
if(start == NULL)
return;
struct Book *current;
if(start->pages == x)
{
Struct Book * temp = start; //save the address of the node to be deleted
start = start->next; //remove the node from the linked list
free(temp->author);
free(...); //whatever memory you want to release
free(temp);
return;
}
for(current = start; current; current = current->next)
{
if(current->next != NULL){
if(current->next->pages == x) {
Struct Book * temp = current->next; //save the address of the node to be deleted
current->next = current->next->next; //remove the node from the linked list
free(temp->author);
free(...); //whatever memory you want to release
free(temp); //free the memory
break;
}
}
}
关于无法从单向链表中删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38201592/