C节点删除问题中的单链表
我在C语言中实现了一个单链表,但一直使用remove node函数。 它删除元素,链接它的两个邻居,但是下面的节点将下一个节点地址设置为NULL。为什么? 有人能帮忙吗C节点删除问题中的单链表,c,data-structures,linked-list,C,Data Structures,Linked List,我在C语言中实现了一个单链表,但一直使用remove node函数。 它删除元素,链接它的两个邻居,但是下面的节点将下一个节点地址设置为NULL。为什么? 有人能帮忙吗 struct node{ struct node* next; int value; }; struct list{ struct node* head; struct node* tail; }; void remove_node(
struct node{
struct node* next;
int value;
};
struct list{
struct node* head;
struct node* tail;
};
void remove_node(struct list* plist, int value){
struct node* current;
struct node* temp;
current = plist->head;
if (!(current)) return;
if ( current->value == value ){
if (!(current->next)){
plist->head = NULL; plist->tail = NULL;
}
else {
plist->head = current->next;
free(current);
}
}
else {
while(current->next){
if(current->next->value==value){
if ((current->next)->next){
temp = current->next;
current->next = (current->next)->next;
free(temp);
}
else{
temp = current->next;
plist->tail = current;
current->next = NULL;
free(temp);
break;
}
}
current = current->next;
}
}
}
Node current current->next
0 0x9f39018 0x9f39028
1 0x9f39028 0x9f39038
2 0x9f39038 0x9f39048
3 0x9f39048 0x9f39058
4 0x9f39058 0x9f39068
5 0x9f39068 0x9f39078
6 0x9f39078 0x9f39088
7 0x9f39088 0x9f39098
8 0x9f39098 0x9f390a8
9 0x9f390a8 (nil)
after remove(5)
0 0x9f39018 0x9f39028
1 0x9f39028 0x9f39038
2 0x9f39038 0x9f39048
3 0x9f39048 0x9f39058
4 0x9f39058 0x9f39078
6 0x9f39078 (nil)
此代码:
if ((current->next)->next){
current->next = (current->next)->next;
free(current->next);
将下一个节点从列表中删除后释放该节点。换句话说,您释放了错误的节点。此代码:
if ((current->next)->next){
current->next = (current->next)->next;
free(current->next);
将下一个节点从列表中删除后释放该节点。换句话说,您释放了错误的节点。请注意,更正后的代码也会在空列表上崩溃。请注意,更正后的代码也会在空列表上崩溃。小心。如果您要删除的号码根本不在列表中,您将尝试使用
If((current->next)->next)
取消对空指针的引用。刚刚到达,感谢您发现空列表上没有崩溃,现在请小心。如果您要删除的号码根本不在列表中,您将尝试使用If((current->next)->next)
取消对空指针的引用。刚刚到达,感谢您发现空列表上没有崩溃