hey guys. ive created this function that will delete the first element it finds in a linked list that has the value n in it. it works except when the number is the FIRST element in the list. it wont delete it, it will replace it with a 0 when i try and print the list for some reason.

the linked list is set out like this.

struct node
{
int number;
node *next;
}

void deleteNumber(node *t, int n)
{

node *current;
node *previous;

previous = NULL;

for (current = t; current!=NULL; previous = current, current = current->next)
{
 if (current->number == n)
 {
     if(previous == NULL)
     {
         t = current->next;
     }
     else
     {
      previous->next = current->next;
     }
     delete current;
     return;
 }




}

}
t = current->next;

This is where your problem lies. Since the memory address 't' is purely local (it's just been pushed onto the stack), when the function returns, the linked list pointer in the parent function will keep pointing to the address of the memory that you deleted.

so how'd i go about fixing it :(

but i thought that creating a pointer to a node called *t would reference the SAME memory location as my start_ptr in my main application. therefore if i change what 't' points to then it changes what start_ptr points to?

>so how'd i go about fixing it
Use either a pointer of a pointer (node **t in your function parameters), or set up your function to return the address of the first node in the list.

>therefore if i change what 't' points to then it changes what start_ptr points to?
You can change the memory that the memory address references, but you can't actually change the memory address itself (which is what you've been attempting to do here). A pointer of a pointer solves this problem because you're indirectly passing the memory address of the node to the function.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.