C语言如何删除双链表中的结点?
How to delete node in double-linked-list by C programming?
struct someEvent
{
int id;
struct someEvent *prev;
struct someEvent *next;
} * someEvent;
struct someEvent *someEventQueue = NULL;
int main(){
//There is some conditions. If passing all of conditions then It is inserted to someEventQueue.
struct someEvent **curr = &someEventQueue;
if ((*curr) != NULL)
{
while ((*curr) != NULL)
{
//After some processes, I want to delete (*curr)
if ((*curr)->prev == NULL && (*curr)->next == NULL)
{
//I don't know how to do this........................
}
if ((*curr)->prev != NULL)
{
(*curr)->next->prev = (*curr)->prev;
}
if ((*curr)->next != NULL)
{
(*curr)->prev->next = (*curr)->next;
}
curr = &(*curr)->next;
}
}
}
我想删除出现在 someEventQueue 中的节点。 someEventQueue 是双向链表。我试图制作一个删除节点代码。但是,我失败了。我不知道为什么,但它 returns 分段错误。如何解决这个问题?
要简单地删除一个节点,您可以这样做:
// dnode is the node to delete
if ((*dnode)->prev != NULL) { // checking if this is the first
(*dnode)->prev->next = (*dnode)->next;
if ((*dnode)->next != NULL) { // checking if this is the last
(*dnode)->next->prev = (*dnode)->prev;
}
} else { // here the node is the first
(*dnode) = (*dnode)->next;
if ((*dnode) != NULL) { // checking if he was the last
(*dnode)->prev = NULL;
}
}
现在您的节点已从链表中删除,但请注意您的游标在列表中的位置并释放dnode
.
struct someEvent
{
int id;
struct someEvent *prev;
struct someEvent *next;
} * someEvent;
struct someEvent *someEventQueue = NULL;
int main(){
//There is some conditions. If passing all of conditions then It is inserted to someEventQueue.
struct someEvent **curr = &someEventQueue;
if ((*curr) != NULL)
{
while ((*curr) != NULL)
{
//After some processes, I want to delete (*curr)
if ((*curr)->prev == NULL && (*curr)->next == NULL)
{
//I don't know how to do this........................
}
if ((*curr)->prev != NULL)
{
(*curr)->next->prev = (*curr)->prev;
}
if ((*curr)->next != NULL)
{
(*curr)->prev->next = (*curr)->next;
}
curr = &(*curr)->next;
}
}
}
我想删除出现在 someEventQueue 中的节点。 someEventQueue 是双向链表。我试图制作一个删除节点代码。但是,我失败了。我不知道为什么,但它 returns 分段错误。如何解决这个问题?
要简单地删除一个节点,您可以这样做:
// dnode is the node to delete
if ((*dnode)->prev != NULL) { // checking if this is the first
(*dnode)->prev->next = (*dnode)->next;
if ((*dnode)->next != NULL) { // checking if this is the last
(*dnode)->next->prev = (*dnode)->prev;
}
} else { // here the node is the first
(*dnode) = (*dnode)->next;
if ((*dnode) != NULL) { // checking if he was the last
(*dnode)->prev = NULL;
}
}
现在您的节点已从链表中删除,但请注意您的游标在列表中的位置并释放dnode
.