Question:
You have been given a pointer to an arbitrary node in a linked list,
which you should delete without corrupting the list. The head of the
list in not given.
ptr
_____ _____ _____ _____ _____
| 1 | -->| 3 | --> | 5 | --> | 7 | -->| 9 | ---
----- ----- ----- ----- ----- |
----
--
Solution:
void del_node ( node_t *ptr )
{
if ( ptr && ptr -> next )
{
node_t *arb = ptr -> next;
ptr -> data = ptr -> next -> data;
ptr -> next = ptr -> next -> next;
free ( arb );
}
else
if ( ptr && ptr -> next == NULL )
{
free ( ptr );
ptr = NULL;
}
return;
}
( Thanks to Prashant N. Gupta )
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
----- Original Message -----
From: "Shyan Lam" <sflam@sbcglobal.net>
To: <C-Guru@yahoogroups.com>
Sent: Tuesday, April 27, 2004 7:21 PM
Subject: RE: [C-Guru] Re: [c-prog] LL problem
Vijay,
In the answer to question 37, the list does not terminate properly if 'ptr'
points to the last node: Setting 'ptr' to NULL does not NULL-terminate the
node before it.
Shyan