简体   繁体   English

LinkedList头节点不断被覆盖C

[英]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. 如果已经看到该单词,则更新其频率,否则,将其以1的频率添加到列表的末尾。该方法开头的print语句应该打印存储在第一个值的单词。 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 . 我使用的测试列表中的文本是a dog and cat ,但第一个打印语句打印出存储在值word变量,即使它应该总是打印出a When I print the entire linked list, all I see is the last word entered, or dog . 当我打印整个链表时,我看到的只是输入的最后一个单词,即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. 我正在发送一个char *,但是char *的值不断变化,每次都会有效地更改头节点的值。 I created a duplicate with strdup and sent that value, at it worked. 我用strdup创建了一个副本,并发送了该值,并且它起作用了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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