简体   繁体   中英

LinkedList head node keeps being overwritten C

I am currently trying to create a linked list, however, for some reason, my head pointer data keeps being overwritten. I have the following method that is supposed to handle insertions into the table and record the frequency of any word that I have come across. If the word has already been seen, then update its frequency, otherwise, add the word to the end of the list with a frequency of 1. The print statement at the beginning of the method is supposed to print the word stored at the first value. The text I am using to test the list is a dog and cat , however the first print statement prints out the value stored in the word variable, even though it should always be printing out a . When I print the entire linked list, all I see is the last word entered, or dog . I am assuming it has something to do with the way I am iterating through the list to see if the word exists or if I have to print, but I cannot figure out how to go around that.

typedef struct tableNode{
  int freq;
  char * word;
  struct tableNode *next;

}tableNode;

void insertIntoTable(char* word){
    if (tableHead != NULL) printf("%s\n", tableHead -> word);
    if (tableHead == NULL){
        printf("Null %s\n", word);
        tableHead = (tableNode*) malloc(sizeof(tableNode));
        tableHead -> word = word;
        tableHead -> freq = 1;
        tableHead -> next = NULL;
        return;
    }

    tableNode* ptr = tableHead;
    while(ptr -> next != NULL){
        if (strcmp(ptr -> word, word) == 0){
            printf("Dup %s %s\n", ptr -> word, word);
            ptr -> freq = (ptr -> freq) + 1;
            return;
        }
        ptr = ptr -> next;
    }
    if (strcmp(ptr -> word, word) == 0){
        printf("Dup %s %s\n", ptr -> word, word);
        ptr -> freq = (ptr -> freq) + 1;
        return;
    }
    printf("New %s\n", word);
    ptr -> next = (tableNode*) malloc(sizeof(tableNode));
    ptr -> next -> word = word;
    ptr -> next -> freq = 1;
    ptr -> next -> next = NULL;
}

Turns out, it wasn't an issue with my method, it was an issue with how I was calling the insertion method. I was sending a char*, but the value of that char* kept changing, effectively changing the value of the head node every time. I created a duplicate with strdup and sent that value, at it worked.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM