user2947605
user2947605

Reputation:

adding items to linked list without allowing duplicates

I have to add items to a linked list without allowing any duplicates:

the list

typedef struct node
{
    double info;
    struct node *next;
} NODE;

my function:

   void addToEnd(NODE **lista, double info)
    {
       NODE *novi = (NODE *) malloc(sizeof(NODE));
       novi->info = info;
       novi->next = NULL;

       if (*lista == NULL)
          *lista = novi;
       else
       {
          NODE *tmp = *lista;
          while (tmp->next)
          {
            if(tmp->info == info)
            {free(new); return;}
             tmp = tmp->next;
          }
          tmp->next = novi;
       }
    }

It does work if the numbers aren't just besides each other, for example adding 5.5 1.0 5.5 works fine, but 5.5 5.5 1.0 adds both of the 5.5, is it a double rounding error or is the code logic flawed ?

Upvotes: 0

Views: 1526

Answers (1)

wildplasser
wildplasser

Reputation: 44240

  • Don't allocate untill you are sure that you actually need the memory
  • avoid special cases. The goal is to find the first (and only) NULL pointer in the chain. This can be *lista (if the list happens to be empty), or some of the ->next pointers.

void addToEnd(NODE **lista, double info)
{
   NODE *new ;

   for (    ; *lista; lista = &(*lista)->next) {
        if((*lista)->info == info) return;
   }
   new = malloc(sizeof *new );
   new->info = info;
   new->next = NULL;
   *lista = new;
}

Or, even more compact (you don't need the new pointer, since you can use the ->next pointer ):

void addToEnd(NODE **lista, double info)
{
   for (    ; *lista; lista = &(*lista)->next) {
        if((*lista)->info == info) return;
   }
   *lista = malloc(sizeof **lista);
   (*lista)->info = info;
   (*lista)->next = NULL;
}

Upvotes: 1

Related Questions