C中的单链表 - 节点删除问题
我正在用 C 实现一个单链表,但被删除节点函数困住了。 它删除该元素,链接其两个邻居,但后面的节点将下一个节点地址设置为 NULL。为什么? 有人可以帮忙吗?
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)
I'm implementing a singly-linked list in C and got stuck with the remove node function.
It removes the element, links two of its neighbours, but the following node gets the next node address set to NULL. Why?
Can anybody help?
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)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
此代码:
将下一个节点从列表中删除后释放它。换句话说,您释放了错误的节点。
This code:
frees the next node after you have already removed it from the list. In other words, you are freeing the wrong node.
请注意,您更正后的代码也会在空列表上崩溃。
Note that your corrected code will also crash on an empty list..