Ethan
Ethan

Reputation: 173

C linked lists - deleting element

if I have a linked list in C and I need to write a function that will delete one of it's elements in the the list (not the first or last one). The list is a global variable, so anywhere I use it it will be changed. If I do a while loop to get to the correct spot and then delete the element, wont the whole list change because I had to move the head to that point?

While doing head = head -> next in the while loop, the pointer is moving element by element and I have no way of going back to the first element once I have finished. So how can I delete an element without erasing part of the list?

Upvotes: 0

Views: 97

Answers (2)

Nepho
Nepho

Reputation: 1122

Two options, off the top of my head :

  • Have the last element point to the first element. This way, no matter what node of your linked list you delete, you can always "go back".

  • Always keep a reference to your first element.

This being said, I don't think having a linked list as a global is a good idea ; is there no other way? Furthermore : is a linked list the right thing for what you're trying to achieve?

Upvotes: 1

anteAdamovic
anteAdamovic

Reputation: 1468

You shouldn't move the global head but rather make a new pointer that will work as a temporary head while iterating through the list.

Lets say the list looks like:

A -> B -> C -> D

If you want to delete C for example, you need to iterate to B (and see that it points to C). Then save it's pointer to C lets call it pC, move on to C and save it's pointer to D lets call it pD.

Then you can simply re-link the list by doing pC = pD so that B now links to D and skips C entirely. That way you remove an element from a linked list.

Your new list will be A -> B -> D.

Just remember to dump the variable before you lose the pointer to it.

Upvotes: 1

Related Questions