954,499 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Search and delete duplicates in linked list

Hello, guys!

I have the following code:

#include<stdio.h>
#include<string.h>
#include<stdlib.h>

struct list_word
{
  char word[64];
  struct list_word * next;
};

typedef struct list_word itemWord;

int main()
{
  itemWord * curr, * head;

  fill list with words
  <strong>remove duplicates</strong>
  show final list of words

  return(0);
}


So I experience difficulties when implementing theremoving duplicates part. What I tried to do is: get (each) word from list, strcmpit to next words, remove if duplicate found. Here is my solution:

curr = head;
  while(curr)
    {
      strcpy(check,curr->word);
      curr = curr->next;
      while(curr)
        {
          if(strcmp(check,curr->word)==0)
            printf("duplicate"); {here should come the remove node function}
          curr = curr->next;
        }
    }


But something is wrong. It compiles without errors, but doesn't say anything about duplicates, even though I know there are. Thanks in advance!

simps0n
Newbie Poster
7 posts since Dec 2007
Reputation Points: 10
Solved Threads: 0
 

you need to keep two different pointers for curr because you have two different loops. Try this:

curr1 = head;
  while(curr1)
    {
      strcpy(check,curr1->word);
      curr2 = curr1->next;
      while(curr2)
        {
          if(strcmp(check,curr2->word)==0)
            printf("duplicate"); {here should come the remove node function}
          curr2 = curr2->next;
        }
        cur1 = cur1->next;
    }
Ancient Dragon
Retired & Loving It
Team Colleague
30,049 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,343
 

Old Thread, but what the heck..

I believe the Remove() function will need a pointer to the node preceding your target.
Kindly design the loops keeping that in mind.

Regards.

masalacurry
Newbie Poster
1 post since Jul 2009
Reputation Points: 7
Solved Threads: 0
 

> Old Thread, but what the heck..
Like reading the rules, but what the heck heh?
http://www.daniweb.com/forums/thread78060.html
"Don't resurrect old threads!"

Salem
Posting Sage
Team Colleague
11,531 posts since Dec 2005
Reputation Points: 5,862
Solved Threads: 953
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You