Search for a node in Linked List

Normally searching can be done using linear search or binary search. But in a linked list, jumping to an intermediate node is not possible. Hence searching should be done sequentially.

Let us assume we have a linked list of names.

struct node
{
   char name[30];
   struct node * next_ptr;
};
typedef struct node * NODEPTR;


In fact it would be better optimized, if we use a dynamic memory for name. For sake of simplicity, let us leave that. Now we have a node pointer called head, which points to the head of the list. And we also have a string search_string. We need to write a function to search this string, and return the pointer to node containing this string. If search string is not found, we must return NULL.

NODEPTR head;
-----
-----
NODEPTR search(NODEPTR head, char *str)
{
      NODEPTR temp;
      for(temp=head;temp!=NULL;temp = temp->next_ptr)
      {
             if(strcmp(temp->name,str)==0)
                  return temp;
      }
      return NULL;
}
We start from first node and compare each node till we find the node containing str. But we should not forget to check for end of list, indicated by NULL.

One step where we may go wrong is comparing temp->name with str instead of using strcmp. If we compare them, then the pointers of these two strings are compared, which will never be equal.

Two more ways of optimization are

  1. Not using temp at all. Instead head itself can be used for list traversal. We need not worry that list would get corrupted. It won't as head is a call by value parameter. 
  2. In for condition adding the clause temp->NULL && strcmp(temp->name,str). If strcmp returns 0, condition is false and loop will terminate. But in this case, the body of for loop will be just a semicolon (;). And return statement will be return temp. If we have reached end of list, then temp will be NULL, so we return NULL. 
You can download the complete program from here

Comments

Popular Posts