Skip to main content

Posts

Showing posts from October, 2012

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 n