问题
As a whole my program is for inserting and deleting nodes in a sorted doubly linked list. Insertion works and deleting the first node from the linked list works fine, except deleting the last node. Also, deleting nodes in the middle and end don't work. If I try to delete the last node, I am led back to main(); If I try deleting a node in the middle, the program crashes. Your help is appreciated!
void remove(int n){
struct node* help = head;
if(head->data == n){
if (head->next)
help->next->prev = NULL;
head = help->next;
} else{
while(help){
if(help->data == n){
if(help->next)
help->next->prev = help->prev;
help->prev->next = help->next;
} else help = help->next;
}
}
}
回答1:
Either you break your while loop or update the help
pointer to next item when if(help->data ==n
is true.
Something like
//your code
...
while(help){
if(help->data == n){
if(help->next)
help->next->prev = help->prev;
help->prev->next = help->next;
//if you don't want to remove all nodes that have data 'n'
break;
}
//if you want to remove all nodes that have data 'n' remove else.
//but keep help = help->next
else
help = help->next;
...
//your code
来源:https://stackoverflow.com/questions/18509733/removing-a-node-from-a-doubly-linked-list-in-c