i started to work on C to get the general idea. i created a linked list structure, i can insert new elements without any problem. the idea of the list is it increments count when there is same element is already inserted, i read the words from a file by the way.
typedef struct Node
{
char* word;
int count;
struct Node *next;
struct Node *head;
struct Node *current;
} Node;
then when i try to use this list in the code below it adds the words but doesn't increments the count. it acts the word as a new element (it increments when i hard code something else multiple times like insertFirst("testString"))
char* pch;
pch = strtok(line," ,.-()\r\n\t");
while (pch != NULL)
{
printf("%s-",pch);
int i = 0;
for(; pch[i]; i++){
pch[i] = tolower(pch[i]);
}
insertFirst(r,(char*) pch,1); // inserts but doesn't increment the count;
pch = strtok (NULL, " ,.-()\r\n\t");
}
the code above reads the file line by line, removes all signs, spaces, new lines etc. i want to put the words in the list "r". i am sure there is not an issue in insertFirst method because it works well without tokenize
//INSERT METHOD-WRONG ONE
void insertFirst(Node* r, char* word, int count){
if(find(r, word)){
struct Node* temp = find(r,word);
temp->count += 1; //
}
else{
struct Node *link = (struct Node*) malloc(sizeof(struct Node));
strcpy(&link->word, &word);
link->count = count;
link->next = r->head;
r->head = link;
}
}
thanks to comments the code below works like a charm
//WORKING INSERT METHOD
void insertFirst(Node* r, char* word, int count){
if(find(r, word)){
struct Node* temp = find(r,word);
temp->count += 1;
}
else{
struct Node *link = (struct Node*) malloc(sizeof(struct Node));
link->word = malloc(strlen(word)+1);
strcpy(link->word, word);
link->count = count;
link->next = r->head;
r->head = link;
}
}
that is the solution that vadim_hr solved
//WORKING INSERT METHOD
void insertFirst(Node* r, char* word, int count){
if(find(r, word)){
struct Node* temp = find(r,word);
temp->count += 1;
}
else{
struct Node *link = (struct Node*) malloc(sizeof(struct Node));
link->word = malloc(strlen(word)+1);
strcpy(link->word, word);
link->count = count;
link->next = r->head;
r->head = link;
}
}