When I delete any node present in a linked list my code works perfectly. let's say my linked list has 10 nodes, if I want to delete 12th, 13th, 14th... nodes my program gives me the expected message.
But if I want to delete 11th node(which is adjacent to the last node), my program terminates with exit code -1073741819 (0xC0000005)
int delete()
{
int position, count = 1;
printf( "\nwrite your position" );
scanf( "%d", &position );
struct node *p, *q;
p = head;
if ( position == 0 ) {
p = p->next;
head = p;
return 0;
}
while ( p != NULL && count != position ) {
count++;
p = p->next;
}
count = 0;
if ( p == NULL ) {
printf( "link list is empty or link not found\n" );
return 0;
}
else {
q = p->next;
p->next = q->next;
}
}
when i delete qny node present in a linked list my code works perfect
No, it doesn't. It looks good for deleting the node at index 0, but for any other positive index n, it attempts to delete the node at index n+1 by advancing pointer p
to point to node n and then manipulating p->next
.
but if i want to delete 11th node(which is adjacent to last node) ,my program terminates with exit code -1073741819 (0xC0000005)
I don't believe that, but I would believe that the program fails when you try to delete the last node (rather than one past the last). In that case, p
is advanced to point to the last node, whose next
pointer is null. Therefore this code:
q=p->next;
p->next=q->next;
sets q
to a null pointer and then attempts to dereference that pointer.
When p
is NULL
then this statement is not valid
p->next = q->next;
so, the solution is adding p->next == NULL
statement to if
condition
like this:-
if ( p == NULL || p->next == NULL ) {
printf( "link list is empty or link not found\n" );
return 0;
}
now the correct code is
int delete()
{
int position, count = 1;
printf( "\nwrite your position" );
scanf( "%d", &position );
struct node *p, *q;
p = head;
if ( position == 0 ) {
p = p->next;
head = p;
return 0;
}
while ( p != NULL && count != position ) {
count++;
p = p->next;
}
count = 0;
if ( p == NULL || p->next == NULL ) {
printf( "link list is empty or link not found\n" );
return 0;
}
else {
q = p->next;
p->next = q->next;
}
}
User contributions licensed under CC BY-SA 3.0