Adding unique values only in linked list in C
typedef struct child {int count; char word[100]; inner_list*next;} child;
typedef struct parent
{ char data [100];
child * head;
int count;
parent * next; } parent;
void append(child **q,char num[100],int size)
{ child *temp,*r,*temp2,*temp3;
parent *out=NULL;
temp = *q;
temp2 = *q;
temp3 = *q;
char *str;
if(*q==NULL)
{ temp = (child *)malloc(sizeof(child));
strcpy(temp->word,num);
temp->count =size;
temp->next=NULL;
*q=temp;
}
else
{ temp = *q;
while(temp->next !=NULL)
{ temp=temp->next;
}
r = (child *)malloc(sizeof(child));
strcpy(r->word,num);
r->count = size;
r->next=NULL;
temp->next=r;
}
}
This is my add function that I use to add an item to my list of children. But my problem is that it should only add unique values followed by a string. It means:
Inputs : aaa bbb aaa ccc aaa bbb ccc aaa
The application must act:
For aaa string there should be a list like bbb->ccc(Not bbb->ccc->bbb since bbb is already there if bbb is coming more than one time it should be increase count only.)
For bbb string there should be list like aaa->ccc only
For ccc string there should be list like aaa only
Hope I can clarify. Any ideas? Please ask for more information.
I tried to check the previous items introduced with the new item. I didn't succeed.
int search(child *p)
{
child *temp= (child *)malloc(sizeof(child));
int var =0;
char num[100];
temp = p;
strcpy(num,p->word);
while(temp->next!=NULL)
{
if(strcmp(temp->word,num)==0)
var =1;
temp=temp->next;
}
return var;
}
This is what I have tried so far. With this search function, I would control if the element is here or not. But it failed.
a source to share
If I understand correctly, given the inputs
aaa bbb aaa ccc aaa bbb ccc aaa
You want the parent list to have 3 items - a child list for aaa
, one for bbb
and one for ccc
.
The list for aaa
must contain all the lines that follow aaa
in the original input, which is simply bbb
and here ccc
. It must contain only one time, with the variable count
at the corresponding nodes incremented so that bbb
count is 2 and ccc
count is 1.
It is right? If so, read on.
for every string S in your input
{
if S is not associated with a child list in the parent
{
create a new child list associated with S at the end of the parent list
}
// now we have C, the child list we either found above or created
if there is a string S' after S
{
find the element S' in the child list C by iterating through it
if you don't find the element S', create/append it with count = 1
else when you find the element, increment its count
}
}
I think this should get you where you want to go.
a source to share