![]() |
Linked List problem - Deleting a node
I have created a simple Linked List. The list stores a username, a IP address associated with the username, and a socket associated with the username. Most of the functions I have created for it work fine except the del() function. I wanted this function to delete a node, but it doesn't delete the node. Could someone show me where I went wrong?
Using OpenWatcom compiler on Windows XP. Here is the code: :
|
Re: Linked List problem - Deleting a node
Quote:
Tip: This is the C forum. |
Re: Linked List problem - Deleting a node
The textbook response to linked list problems is to draw it out on paper, then walk through your code on said paper and see what happens. Your problem is fairly easy if you're looking at a picture. Hint: you're breaking the chain instead of removing a link.
Side note about style: using a global variable for current_ptr is a poor practice. Your code would be better if you declared a local variable in each function where you iterate over the list. |
Re: Linked List problem - Deleting a node
Quote:
|
Re: Linked List problem - Deleting a node
peaceofpi was most likely referring to the author's use of cout (part of the C++ standard) and the "new" operator (C++ only), among other possible inconsistencies with C.
|
Re: Linked List problem - Deleting a node
> Could someone show me where I went wrong?
Well you had a linked list which looked like this :
+=====+ +=====+ +=====+ +=====+ +=====+ What you should end up with, after deleting 'D' is :
+=====+ +=====+ +=====+ +=====+ But instead, you've got :
+=====+ +=====+ +=====+ You can't just blow away the node you want to delete, you need to repair the pointer chain to jump over the node you're going to delete, before you delete it. You also need some extra care when the node being deleted is also the head node in the list. |
Re: Linked List problem - Deleting a node
Sorry, Salem, you missed the real problem ...
There is also a problem that will emerge when creating the list. head_ptr is never initialised so it points to anything valid (i.e. a data structure). The first call to add_user will therefore introduce undefined behaviour. The code that creates a struct pointed at by current is fine, although it stores the address of the created struct in a local variable. Then move_current_to_end() is called, which does; :
current_ptr=head_ptr; |
Re: Linked List problem - Deleting a node
Ok, I have revised the code a bit, and I still having problems with the del() function.
:
|
Re: Linked List problem - Deleting a node
You need to keep track of the last_ptr. Then when you delete, last_ptr.next is loaded with current_ptr.next before you delete current_ptr.
|
Re: Linked List problem - Deleting a node
Thanks for all of the help, I finally got it to work. Here is the code:
:
|
| All times are GMT -5. The time now is 3:26 PM. |
Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC