The word caterpillar is not getting loaded in the hashtable on index 2 next to cat when small dictionary is used , i have already written code for insertion in the beginning i.e cat is already loaded on index 2.


   { if(cur->word >=new_node->word)

      { prev=cur;


You don't compare strings using the relational operators, but rather, you may use strcmp (declared in string.h).

Also, apparently there's a problem with the logic of the insertion here.

For example, assuming you fixed the first problem, if the condition inside the while loop is true, you're assigning cur to prev, assigning cur to new_node->next which makes sense because if cur->word comes after new_node->word in the dictionary, you want new_node->next to point to cur, but after that, you're assigning new_node to prev->next which is the same as cur->next. So now you're having new_node->next pointing to cur and cur->next pointing to new_node which apparently doesn't make sense.

Also, after the loop ends execution, you're setting new_node->next to NULL anyway which isn't probably a good thing in case new_node->next was already set to a non-NULL pointer inside the loop.

Lastly, in case the condition inside the loop were never true (i.e., the node should be inserted at the end of the list), cur keeps traversing through the list until it becomes NULL. Then all you're doing is setting cur to new_node which doesn't have any effects on the list. If the previous point wasn't clear enough, you may look at the following code

cur = hashtable[hashvalue]; // set cur to the start of the list

// keep traversing till the end of the list
while (cur != NULL)
    cur = cur->next;

// cur now points to NULL
cur = new_node; // cur now points to new_node which doesn't have effects on the list

Keep in mind that in a singly-linked-list, you can only access a node through a previous node.

To make things clearer, hopefully, the 3 main cases that you should rethink about are

  1. whether the list is empty (aka the first insertion).
  2. inserting a node in the middle of the list.
  3. inserting a node at the end of the list.

Hope that helps!

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .