Finding a data in a linked list

Hi guys, I would just like to ask. If let's say, I had a list with the following elements:

1, 2, 4, 6, 3, 8

and I wanted to look for 6. I traverse the list from the start node, and go through 1, 2, 4 and then 6. And then that's when I stop traversing the list, right? Now, when I stopped traversing the list, is the address of the 4th node (where the 6 is) saved in memory? If let's say I had my structure laid like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
struct Node{
  int data;
  struct Node *next;
} *start;

void deleteData(int x){
  ...
  findNode(x);
}

void findNode(){
struct Node *jumper;
  ...
}


You see, what I'm trying to do is:
- user keys in the value he wants to delete
- find if the value exists in the list
- delete the value from the list (and any possible re-occurrences)

So, I sort of need to get the address of the last node that I passed from the findNode() back to deleteData() because I need to delete/free that particular node.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
struct Node * find( struct Node *start, int value )
{
   while ( start && !( start->data == value ) ) start = start->next;

   return ( start );
}

struct Node * delete( struct Node *start, int value )
{
   struct Node *target = find( start, value );

   if ( target )
   {
      struct Node *tmp = target;
      target = target->next;
      free( tmp );
   }

   return ( target );
}   
I advice to read "Data Structures & Algorithms in Java" by Robert Lafore.
If you need to delete all occurences of a value in the list then you can write

1
2
3
4
void delete_all( struct Node *start, int value )
{
   while ( start = delete( start, value ) );
} 


Or even it would be better to write it as

1
2
3
4
void delete_all( struct Node *start, int value )
{
   while ( ( start = delete( start, value ) ) != NULL );
} 
Last edited on
Topic archived. No new replies allowed.